سؤال

This is code of copying data of one file into second file

      public class Writer 
      {
          public static void main(String args[]) throws IOException
          {
              File f=new File("D:/test.txt");
              FileReader fr=new FileReader(f);
              char cbuff[]=new char[100];
              int c=fr.read(cbuff);
              System.out.println(c);
              c=fr.read(cbuff);
              System.out.println(c);
              fr.close();

              FileWriter fw=new FileWriter("D:/newTest.txt");
              fw.write(cbuff);
              fw.close();
          }   
      }

The output is
67
-1
My first question is
I wanna know that size of char array is 1000 so why does read method returns -1 second time.

My second question is Acc. to [Java Docs] (http://docs.oracle.com/javase/7/docs/api/java/io/Reader.html#read%28java.nio.CharBuffer%29)

or -1 if this source of characters is at its end


What is the meaning of the above line?

هل كانت مفيدة؟

المحلول

I wanna know that size of char array is 1000 so why does read method returns -1 second time.

Because the input stream contains no more characters to read. Note that if there were a second read, you would overwrite the contents already read into the array.

And your javadoc points to the wrong method. You use the read() method taking a char[] as an argument. A CharBuffer is not a char[]!

Finally (and you have asked a question about such a subject recently and I have already told you that), you should specify the encoding you are using for both reading the file and writing to the file.

نصائح أخرى

when you do this:

fr.read(cbuff);

Since you have only 67 chars, You have read the whole file, so the next time the cursor will be at the end of the file, so it returns -1. in another world there is nothing left to read.

When first time you are reading by fr.read(cbuff) then it's reading characters in the file and total char are 67 so it's showing 67 now cursor moves to end of file next time when you are reading then it found EOF that's why returning -1.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top