需求背景:多次向文件中依次寫入內容,
需求分析:如何向文件中依次追加內容呢?而且不清空之前的內容。
今天就分享一下基於Java語言,如何在文件末尾追加內容。
import java.io.*;
public class AddContent2TxtLast {
/**
* "\\r\\n"用於換行
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// 可以是其它格式的文件
String pathName = "D:\\img\\test.txt";
String conent = "\r\n測試,把字符追加到文件末尾";
addContentPlus(pathName, conent);
conent = "\r\naddContent2TxtLast";
addContent2TxtLast(pathName, conent);
conent = "\r\nmethod2";
method2(pathName, conent);
}
/**
* 追加文件內容:<p>
* 判斷文件是否存在,不存在則創建<p>
* 使用FileOutputStream,在構造FileOutputStream時,把第二個參數設為true<p>
*
* @param pathName
* @param conent
*/
public static void addContentPlus(String pathName, String conent) throws IOException {
File file = new File(pathName);
// 判斷文件不存在,返回
if (!judeFileExists(file)) {
return;
}
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true)));
out.write(conent);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 追加文件:使用FileOutputStream,在構造FileOutputStream時,把第二個參數設為true,表示在文件末尾追加
*
* @param pathName
* @param conent
* @throws IOException
*/
public static void addContent2TxtLast(String pathName, String conent) throws IOException {
FileOutputStream fos = new FileOutputStream(pathName, true);
fos.write(conent.getBytes());
fos.flush();
fos.close();//流要及時關閉
}
/**
* 追加文件:使用FileWriter
*
* @param pathName
* @param content
*/
public static void method2(String pathName, String content) throws IOException {
FileWriter writer = null;
try {
// 打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
writer = new FileWriter(pathName, true);
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
} finally {
writer.flush();
writer.close();
}
}
// 判斷文件是否存在
public static boolean judeFileExists(File file) {
if (file.exists()) {
System.out.println("File exists");
return Boolean.TRUE;
} else {
System.out.println("File not exists, please create it ...");
return Boolean.FALSE;
}
}
}
如果遇到文件目錄不存在的場景,請參考《當文件不存在時自動創建文件目錄和文件》的解決策略。