Java, the write fileoutputstream println () and () as a result of different question.

Asked 2 years ago, Updated 2 years ago, 94 views

Hello, I'm a student studying Java from the beginning.

I'm just copying each and every one of them while reading a book, and I'm asking you a question because I have a question while studying Stream.

import java.io.FileOutputStream;

public class TestCode {
    static public void main(String[] args) throws Exception{
        FileOutputStream fos = new FileOutputStream("test.txt");
        byte[] data = "ABC".getBytes();
        for(int i = 0; i < data.length; i++){
            System.out.println(data[i]);
            fos.write(data[i]);
        }
        fos.flush();
        fos.close();
    }
}

The description of write(intb) in Java 8 document is as follows.

Writes the specified byte to this file output stream.

In the above code, System.out.println (data[i]); syntax outputs 65, 66, and 67, respectively. And ABC is printed in the text.txt file.

Why is ABC printed on test.txt instead of 65, 66, and 67? What is the difference between printing to the console with println() and printing to the file with write()?

I hope you teach a lot of things.

Thank you.

java stream

2022-09-22 19:30

1 Answers

It's easy if it's easy, but difficult if it's difficult.

Unless it is a binary file (.exe file, for example), it must be written as a letter to write to a file.

If it's 65, it's A with the ASCII code. That is, it has to be written in characters, so it has been converted to char.

If you explicitly transform println as below, it will look like an alphabet.

println((char)data[i]);


2022-09-22 19:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.