Java 文件输出流
Java ⽂件输出流
Java IO教程 - Java⽂件输出流
创建输出流
要写⼊⽂件,我们需要创建⼀个FileOutputStream类的对象,它将表⽰输出流。
// Create a file output stream
String destFile = "test.txt";
FileOutputStream fos = new FileOutputStream(destFile);
当写⼊⽂件时,如果⽂件不存 ,Java会尝试创建⽂件。我们必须准备好处理这个异
常,将代码放 try-catch块中,如下所⽰:
try {
FileOutputStream fos = new FileOutputStream(sr File);
} at h (FileNotFoundEx eption e){
// Error handling ode goes here
}
如果⽂件包含数据,数据将被擦除。为了保留现有数据并将新数据附加到⽂件,我们
需要使⽤FileOutputStream类的另⼀个构造函数,它接受⼀个布尔标志,⽤于将新数据
附加到⽂件。
要将数据附加到⽂件,请 第⼆个参数中传递true,使⽤以下代码。
FileOutputStream fos = new FileOutputStream(destFile, true);
写数据
FileOutputStream类有⼀个重载的write()⽅法将数据写⼊⽂件。我们可以使⽤不同版本
的⽅法⼀次写⼊⼀个字节或多个字节。
通常,我们使⽤FileOutputStream写⼊⼆进制数据。
要向输出流中写⼊诸如“Hello"的字符串,请将字符串转换为字节。
String类有⼀个getBytes()⽅法,该⽅法返回表⽰字符串的字节数组。我们给
FileOutputStream写⼀个字符串如下:
String text = "Hello";
byte[] textBytes = text.getBytes();
fos.write(textBytes);
要插⼊⼀个新⾏,使⽤line.separator系统变量如下。
String lineSeparator = System.getProperty("line.separator");
fos.write(lineSeparator.getBytes());
我们需要使⽤lush()⽅法刷新输出流。
fos.flush();
刷新输出流指⽰如果任何写⼊的字节被缓冲,则它们可以被写⼊数据宿。
关闭输出流类似于关闭输⼊流。我们需要使⽤close()⽅法关闭输出流。
// Close the output stream
fos. lose();
close()⽅法可能抛出⼀个IOException异常。如果我们希望⾃动关闭tit,请使⽤try-with-
resources创建输出流。
以下代码显⽰如何将字节写⼊⽂件输出流。
import java.io.File;
import java.io.FileOutputStream;
publi lass Main {
publi stati void main(String[] args) {
String destFile = "lu i2.txt";
// Get the line separator for the urrent platform
String lineSeparator = System.getProperty("line.separator");
String line1 = "test";
String line2 = "test1";
String line3 = "test2";
String line4 = "test3";
try (FileOutputStream fos = new FileOutputStream(destFile)) {
fos.write(line1.getBytes());
fos.write(lineSeparator.getBytes());
fos.write(line2.getBytes());
fos.write(lineSeparator.getBytes());
fos.write(line3.getBytes());
fos.wri