赞
踩
1. FileWritter写入文件
FileWritter, 字符流写入字符到文件。默认情况下,它会使用新的内容取代所有现有的内容,如下:
new FileWriter(file);
然而,当指定一个true (Boolean)值作为FileWritter构造函数的第二个参数,它会保留现有的内容,并追加新内容在文件的末尾,如下:
new FileWriter(file,true);
举个例子:
一个文件名为test_appendfile.txt,包含以下内容:Hello World,需要追新内容,代码如下:
- package com.andy.file;
-
-
-
- import java.io.File;
-
- import java.io.FileWriter;
-
- import java.io.BufferedWriter;
-
- import java.io.IOException;
-
- public class AppendToFileTest
-
- {
-
- public static void main( String[] args )
-
- {
-
- try{
-
- String content = "A cat will append to the end of the file";
-
- File file =new File("test_appendfile.txt");
-
- if(!file.exists()){
- file.createNewFile();
- }
-
- //使用true,即进行append file
-
- FileWriter fileWritter = new FileWriter(file.getName(),true);
-
-
- fileWritter.write(content);
-
- fileWritter.close();
-
- System.out.println("finish");
-
- }catch(IOException e){
-
- e.printStackTrace();
-
- }
-
- }
-
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
执行结果:
可打开文本文件“test_appendfile.txt”,内容更新如下:
Hello world A cat will append to the end of the file
2.BufferedWriter写入文件
缓冲字符(BufferedWriter )是一个字符流类来处理字符数据, 但又不同于字节流(数据转换成字节),你可以直接写字符串,数组或字符数据保存到文件。
- package com.andy.file;
-
-
- import java.io.BufferedWriter;
-
- import java.io.File;
-
- import java.io.FileWriter;
-
- import java.io.IOException;
-
- public class WriteToFileTest2 {
-
- public static void main(String[] args) {
-
- try {
- String content = "a dog will be write in file";
- File file = new File("test_appendfile2.txt");
- if(!file.exists()){
- file.createNewFile();
- }
- FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
- BufferedWriter bw = new BufferedWriter(fileWriter);
- bw.write(content);
- bw.close();
- System.out.println("finish");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
执行完后,打开test_appendfile2.txt文件即可看到。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。