gpt4 book ai didi

java 缓冲输出流

转载 作者:行者123 更新时间:2023-12-02 13:01:06 25 4
gpt4 key购买 nike

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

}
}

但是这段代码的结果是真空。

我认为第一个代码和第二个代码非常相似。

为什么它(第二个代码)不能正常工作?

最佳答案

您忘记关闭 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 中使用。

关于java 缓冲输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44289660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com