问题
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