PrintStream write(int i) method doesn't work?

老子叫甜甜 提交于 2020-06-03 17:26:13

问题


I'm learning about I/O and the stream abstraction. I came across this little toy example which should open a stream attached to a text file and display the content (simple ASCII text) to the default destination attached to System.out, the console.. It doesn't display a thing,where am I wrong?

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;


public class Test {

public static void main(String[] args) throws IOException {
    InputStream in=new FileInputStream("readme.my");
    while (true) {
        int byteRead=in.read();
        if (byteRead==-1) break;
        System.out.write(byteRead);
    }
}
}

回答1:


The `System.out.write(byteRead); call writes a byte as-is (without doing any conversion) to the standard output stream for your application. The output stream's character encoding depends on how you have configured your system.

  • If you are reading from a binary file, there is a good chance that it contains no printable characters ... depending on the default character encoding.

  • The file could be empty.

If you are trying to display as decimal bytes, then you should be using a print method; please the javadocs for PrintStream.


It is also possible that the problem is that the System.out stream is not being flushed, and hence some data is not being output. Try calling flush() after the loop exits.

(The System.out and/or System.err streams maybe configured to autoflush each time they see a newline. However, if your input file contains no newlines, that won't happen.)


( I thought it was automatically flushed on program termination..).

It is not a good idea to rely on "I though that ...". Check the javadocs. In this case, the javadocs for System.out do not specify that this happens, so your assumption is beyond the "spec".



来源:https://stackoverflow.com/questions/30414066/printstream-writeint-i-method-doesnt-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!