java文件相关(文件追加内容、文件内容清空、文件内容读取)
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;
}