Java 文件字节输出流:写入文件内容 - 代码示例
使用文件字节输出流进行输入操作的基本步骤如下:
- 创建文件字节输出流对象,指定要输出的文件路径。
FileOutputStream fos = new FileOutputStream("path/to/file.txt");
- 创建一个字节数组,用于存储要输出的数据。
byte[] data = "Hello, World!".getBytes();
- 使用文件字节输出流的write方法将数据写入文件。
fos.write(data);
- 关闭文件字节输出流。
fos.close();
完整示例代码如下:
import java.io.FileOutputStream;
import java.io.IOException;
public class ByteOutputStreamExample {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
// 创建文件字节输出流对象
fos = new FileOutputStream("path/to/file.txt");
// 准备要输出的数据
byte[] data = "Hello, World!".getBytes();
// 将数据写入文件
fos.write(data);
System.out.println("写入文件成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭文件字节输出流
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
注意:在使用文件字节输出流进行写入操作时,如果指定的文件路径不存在,则会自动创建该文件。如果文件已经存在,那么会覆盖原有的文件内容。
原文地址: https://www.cveoy.top/t/topic/p7lo 著作权归作者所有。请勿转载和采集!