https://blog.csdn.net/xnz0616/article/details/39137177
1、檔案內容追加
// 在已有的檔案後面追加資訊
public static void appendInfoToFile(String fileName, String info) {
File file =new File(fileName);
try {
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWriter =new FileWriter(file, true);
info =info +System.getProperty("line.separator");
fileWriter.write(info);
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2、檔案內容清空
// 清空已有的檔案內容,以便下次重新寫入新的內容
public static void clearInfoForFile(String fileName) {
File file =new File(fileName);
try {
if(!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter =new FileWriter(file);
fileWriter.write("");
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
3、讀取檔案內容,檔案中的內容為String
public static List<String> readInfoFromFile(String fileName) {
File file =new File(fileName);
if(!file.exists()) {
return null;
}
List<String> resultStr =new ArrayList<String>();
try {
BufferedReader bufferedReader =new BufferedReader(new FileReader(file));
String str =null;
while(null !=(str=bufferedReader.readLine())) {
resultStr.add(str);
}
}catch (IOException e) {
e.printStackTrace();
}
return resultStr;
}