创建输出流
要写入文件,需要创建一个FileOutputStream
类的对象,它将表示输出流。
// Create a file output stream
String destFile = "test.txt";
FileOutputStream fos = new FileOutputStream(destFile);
当写入文件时,如果文件不存在,Java会尝试创建文件。但必须要处理这个异常,将代码放在try-catch
块中,如下所示:
try {
FileOutputStream fos = new FileOutputStream(srcFile);
}catch (FileNotFoundException e){
// Error handling code goes here
}
如果文件包含数据,数据将被擦除。 为了保留现有数据并将新数据追加到文件,需要使用FileOutputStream
类的另一个构造函数,它接受一个布尔标志,用于将新数据附加到文件。
要将数据追加到文件,请在第二个参数中传递true
,使用以下代码。
FileOutputStream fos = new FileOutputStream(destFile, true);
写入数据
FileOutputStream
类有一个重载的write()
方法将数据写入文件。可以使用不同版本的方法一次写入一个字节或多个字节。
通常,使用FileOutputStream
写入二进制数据。要向输出流中写入诸如“Hello”
的字符串,请将字符串转换为字节。String
类有一个getBytes()
方法,该方法返回表示字符串的字节数组。使用FileOutputStream
写一个字符串如下:
String destFile = "test.txt";
FileOutputStream fos = new FileOutputStream(destFile, true);
String text = "Hello";
byte[] textBytes = text.getBytes();
fos.write(textBytes);
要插入一个新行,使用line.separator
系统变量如下。
String lineSeparator = System.getProperty("line.separator");
fos.write(lineSeparator.getBytes());
需要使用flush()
方法刷新输出流。
fos.flush();
刷新输出流指示任何写入的字节缓冲清出,将数据可以写入目标处。关闭输出流类似于关闭输入流。需要使用close()
方法关闭输出流。
// Close the output stream
fos.close();
close()
方法可能抛出一个IOException
异常。如果希望自动关闭,请使用try-with-resources
创建输出流。
以下代码显示如何将字节写入到文件输出流。
import java.io.File;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) {
String destFile = "destfile.txt";
// Get the line separator for the current 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.write(lineSeparator.getBytes());
fos.write(line4.getBytes());
// Flush the written bytes to the file
fos.flush();
System.out.println("Text has been written to "
+ (new File(destFile)).getAbsolutePath());
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
上面的代码生成以下结果。
Text has been written to F:\website\yiibai\worksp\destfile.txt
F:\website\yiibai\worksp\destfile.txt
文件的内容如下: