Java读取、写入txt文件
原创
©著作权归作者所有:来自51CTO博客作者某科学的南条的原创作品,请联系作者获取转载授权,否则将追究法律责任
1、读取
public String GetLogString(String logpath){
System.out.println("----------------开始读取日志----------------");
File logfile = new File(logpath+"\\log.txt");
String totalstr = "";
if(logfile.exists()){
try {
FileReader fr = new FileReader(logfile);
BufferedReader br = new BufferedReader(fr);
String line = "";
while ((line = br.readLine()) != null){ //按行读取文件流的内容
totalstr = totalstr + line +",";
}
fr.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}else{
System.out.println("日志文件不存在");
}
return totalstr;
}
2、追加写入
/**
* 写入TXT,追加写入
* @param filePath
* @param content
*/
public static void fileChaseFW(String filePath, String content) {
try {
//构造函数中的第二个参数true表示以追加形式写文件
FileWriter fw = new FileWriter(filePath,true);
fw.write(content);
fw.close();
} catch (IOException e) {
System.out.println("文件写入失败!" + e);
}
}
public static void main(String[] args) throws Exception{
File file = new File("D:\\123wu吴.txt");
createFile(file);
readTxtFile(file);
fileChaseFW("D:\\123wu吴.txt","66666666");
}
}
3、覆盖写入
/**
* 写入TXT,覆盖原内容
* @param content
* @param fileName
* @return
* @throws Exception
*/
public void writeTxtFile(String content,File fileName)throws Exception{
FileWriter fw = new FileWriter(fileName);
fw.write(content);
fw.close();
}