package byte_base;
import java.io.FileInputStream;
import java.io.IOException;
public class FileViewer {
public static void main(String[] args) {
int a;
try{
FileInputStream fis = new FileInputStream("FileViewerln.txt");
while((a = fis.read())!=-1){
System.out.write(a);
}
}catch(IOException ioe){
System.err.println(ioe);
ioe.printStackTrace();
}
}
}它是程序,从文件中打印文本。当我使用FileInputStream类和System.out.write()方法时,它运行得很好。
但我试过另一种方法。我使用了BufferedOutputStream而不是System.out.write()方法。
底部是使用BufferedOutputStream类编写的代码。
package byte_base;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class CopyOfFileViewer {
public static void main(String[] args) {
int a;
try{
FileInputStream fis = new FileInputStream("FileViewerln.txt");
BufferedOutputStream bos = new BufferedOutputStream(System.out);
while((a = fis.read())!=-1){
bos.write(a);
}
}catch(IOException ioe){
System.err.println(ioe);
ioe.printStackTrace();
}
}
}但是这段代码的结果是vacuum。
我认为第一个代码和第二个代码非常相似。
为什么它(第二个代码)不能正常工作?
发布于 2017-06-01 00:12:11
您忘记关闭OutputStream bos。
bos.close();实际上,在try-with-resources中执行操作要好得多
try (FileInputStream fis = new FileInputStream("FileViewerln.txt");
BufferedOutputStream bos = new BufferedOutputStream(System.out);
) {
while((a = fis.read())!=-1){
bos.write(a);
}
} catch(IOException ioe){
System.err.println(ioe);
ioe.printStackTrace();
}类InputStream实现了Closeable。因此,它的子类可以在try-with-resources中使用。
发布于 2017-06-01 00:10:58
啊,古老的flush和Buffered Stream问题。
使用flush方法。
将其放在while循环之后
bos.flush();
从文档中
该类实现了一个缓冲的输出流。通过设置这样的输出流,应用程序可以将字节写入底层输出流,而不必为写入的每个字节调用底层系统。
这里的关键点是
,而不必为写入的每个字节调用底层系统。
这基本上意味着数据在内存中缓冲,而不是在每次write方法调用时写入输出流。
您应该以适当的时间间隔刷新缓冲区,并使用close方法关闭流,以强制输出最终的缓冲区。
https://stackoverflow.com/questions/44289660
复制相似问题