sinex
sinex

Reputation: 75

A code I don't understand about the write method in I/O

I just started learning IO and there's something about this code I don't understand:

public static void main(String[] args) throws IOException {


    FileReader reader = new FileReader("C://blablablal.txt");
    FileWriter writer = new FileWriter("C://blabla.txt");


        int c;
        while ((c = reader.read()) != -1) {
            writer.write(c);

        }
    reader.close();
    writer.close();

}

I'll be happy for an explenation of how does the write method, which writes "c"(an int) in the while loop, actually writes it as a character or a string in the txt file. Thanks

Upvotes: 0

Views: 44

Answers (3)

JeramyRR
JeramyRR

Reputation: 4461

reader.read() is reading one character from a file at a time. This seems a little confusing because you are reading a character in as an integer value, but all this means really is that the integer value equates to a character. When there are no more characters to read in the file a -1 is returned and this is how you know you've reached the end of the file.

writer.write behaves the same way. It writes the integer value of a character to a file.

Here is a link to a good tutorial on Java IO FileReader. And here is one for Java IO FileWriter.

Upvotes: 2

Kayaman
Kayaman

Reputation: 73558

The write(int c) method casts the int (32 bits) to a char (16 bits). The char is then converted to appropriate bytes depending on the encoding. In this case the encoding used is the platform default encoding, but you should always specify the encoding used to make sure that it will work properly in any environment.

The reason it doesn't take char c as a parameter is apparently a design oversight which is too late to correct now.

Upvotes: 2

Pavan
Pavan

Reputation: 135

Firstly, FileReader will be ready to read the content of the File at the given file path if the path is correct.
Secondly,FileWriter will be ready to write the something to the File if it has something to write.

Next, The reader reads the contents from the File until the end of the File(-1) and writes to another file using writer.

Atlast the Reader and Writer will get closed.

Comment here if you have any Doubts.

Upvotes: 2

Related Questions