提示
Java IO FileOutputStream 使用示例。@ermo
# FileOutputStream 使用示例
FileOutputStream
是 InutStream
的实现类,用于将数据输出到文件中。
常用的构造方法有:
public FileOutputStream(String name)
public FileOutputStream(String name, boolean append)
public FileOutputStream(File file) throws FileNotFoundException
FileOutputStream(String name)
会根据指定文件名 name
创建一个输出流。
FileOutputStream(String name, boolean append)
除了根据文件名 name
创建输出流外,如果第二个参数 append
为 true
,输出的数据将会追加到现有文件内容后,而不是覆盖文件内容。
public FileOutputStream(File file)
可以通过 file
对象创建一个输出流。
FileOutputStream
最核心的方法就是 write()
方法,主要有3个重载方法:
public void write(byte b[]) throws IOException
public void write(byte b[], int off, int len)
public void write(int b) throws IOException
write(int b)
向流中写入1个字节,底层会调用 FileOutputStream
的本地方法。
write(byte b[])
批量向流中写入 b[]
个字节。
write(byte b[], int off, int len)
批量向流中写入 b[]
个字节,第一个写入的字节为 b[off]
,写入字节的个数为 len
。
来看一个简单的例子:
/**
* Write text by FileOutputStream.
*/
public static void write() {
String dir = System.getProperty("user.dir");
String str = "Write some text.\nWrite another text again.";
OutputStream fos = null;
try {
fos = new FileOutputStream(dir + File.separator + "src/main/resources/output.txt", true);
byte[] bytes = str.getBytes();
fos.write(bytes);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
write();
}
output.txt
输出内容:
Write some text.
Write another text again.
上例中的 write()
如果多次调用,str
中的文本会被追加到 output.txt
文件中。
flush()
方法可以确保输出流中的数据全部写入 output.txt
中。
close()
方法确保输出流使用完毕后对系统资源进行释放,调用 close()
方法一般先调用 flush()
方法,并且应该将 flush()
和 close()
放到 finally
语句块中。