知识点介绍
文件输出流是用于将数据写入 File 或 FileDescriptor 的输出流。文件是否可用或能否可以被创建取决于基础平台。特别是某些平台一次只允许一个 FileOutputStream(或其他文件写入对象)打开文件进行写入。在这种情况下,如果所涉及的文件已经打开,则此类中的构造方法将失败。
FileOutputStream 用于写入诸如图像数据之类的原始字节的流。要写入字符流,请考虑使用FileWriter。
请自行查阅相关知识点。
本次演示功能介绍
1. 使用fileoutputstream定义文件并且写入一些字符。
2. 全部替换文件内的字符。
3. 拼接文件内的字符,每次appaend.
全部替换文件内的字符
@Test
public void writeFile(){
// 创建OutputStream对象
FileOutputStream fileOutputStream = null;
String filePath = "C:\\Users\\JinZh\\IdeaProjects\\TestJa\\software\\file02.txt";
try {
fileOutputStream = new FileOutputStream(filePath);
// 写入一个字节
String str = "hello xiaoyu " + System.currentTimeMillis();
fileOutputStream.write(str.getBytes());
System.out.println("写文件成功 : " + str);
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
拼接文件内的字符
只需要将构造器加一个参数即可。采用以下构造器。
public FileOutputStream(String name, boolean append)
throws FileNotFoundException
{
this(name != null ? new File(name) : null, append);
}
那么,在上一份代码中我们只需要改动这一行代码,添加一个true参数。
fileOutputStream = new FileOutputStream(filePath);
fileOutputStream = new FileOutputStream(filePath, true);