Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 views
in Technique[技术] by (71.8m points)

java - How to reopen a file from a input stream

I want to re-open a file. I have a file in Input stream. I have tried using Scanner and using BufferedReader. But I am unable to open the file again after it is closed using close() method. Please help how to open a file again. I have written the below code:

InputStream filename = getAttachstream();

        int rows =0 ;

        BufferedReader br= new BufferedReader(new InputStreamReader(filename));
        String strLine = "";
          try {
            while( (strLine = br.readLine()) != null) {
                rows++;
              }
            //br.reset();
            br.close();
            //br.reset();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
if(rows>0){
            InputStream filename1 = getAttachstream();
            Scanner inputStream1 = new Scanner(filename1);
                for (int rowIncr = 1; inputStream1.hasNext(); rowIncr++) {

                String data;
                try {
                    data = br.readLine();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String [] values = data.split(",");
                String curRowPartNumber = values[0];
                String curRowQuantity =   values[1];
                if(rowIncr == 1)
                {
                    if((values[0]==null || values[0].trim().length()<=0)
                            || (values[1]==null || values[1].trim().length()<=0)
                            || (values[2] != "") || !"Part Number".equalsIgnoreCase(values[0].trim())
                            || !"Quantity".equalsIgnoreCase(values[1].trim())){
                        System.out.println("Invalid Excel sheet data");
                        throw new ECApplicationException(ECMessage._ERR_CMD_INVALID_DATAFORMAT, CLASSNAME,methodName);
                    }

                }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Once a stream, reader, writer, socket or any other resource has closed, you can't open it again.

If you want to read a file more than once, you need to have its file name.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...