通过字节流往桌面上的文本文件写入数据。要求:一定关闭流
时间: 2023-06-04 07:04:31 浏览: 50
你好,关于你的问题,我可以给出以下的代码示例:
```
import java.io.*;
public class Main {
public static void main(String[] args) {
String data = "Hello, world!"; // 要写入文件的数据
File file = new File("C:\\Users\\user\\Desktop\\output.txt"); // 设置输出文件的路径
OutputStream os = null;
try {
os = new FileOutputStream(file); // 打开输出流
byte[] bytes = data.getBytes(); // 获得数据的字节数组
os.write(bytes); // 将数据写入输出流
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close(); // 关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
```
上述代码将数据字符串写入到桌面上的 output.txt 文件中,并且在写入结束后关闭了流。建议在使用完流之后一定要关闭流对象,避免资源的浪费和泄露。
希望可以帮助到你,如果你有其他问题,可以继续问我哦。