PrintStream write(int i)方法不起作用? [英] PrintStream write(int i) method doesn't work?

查看:118
本文介绍了PrintStream write(int i)方法不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习I/O和流抽象. 我遇到了这个小玩具示例,该示例应打开附加到文本文件的流,并显示内容(简单的ASCII文本)到附加到控制台System.out的默认目标位置. 它没有显示任何东西,我在哪里错了?

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);
    }
}
}

推荐答案

`System.out.write(byteRead); call会按原样(不进行任何转换)将字节写入应用程序的标准输出流.输出流的字符编码取决于您如何配置系统.

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.

文件可能为空.

如果试图显示为十进制字节,则应使用print方法;否则,请使用print方法.请 javadocs 用于PrintStream.

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

问题还可能是未刷新System.out流,因此未输出某些数据.循环退出后,尝试调用flush().

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.

(System.out和/或System.err流可以配置为在每次看到换行符时自动刷新.但是,如果您的输入文件不包含换行符,则不会发生.)

(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..).

依靠我虽然..."不是一个好主意.检查javadocs.在这种情况下,System.out的javadocs没有指定发生这种情况,因此您的假设超出了规范".

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".

这篇关于PrintStream write(int i)方法不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆