FileWriter 追加文件及文件改名
我就廢話不多說了,大家還是直接看代碼吧~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileWriterUtil { /** * 追加文件:使用FileWriter */ public static void appendMethod(String fileName, String content) { try { //打開一個(gè)寫文件器,構(gòu)造函數(shù)中的第二個(gè)參數(shù)true表示以追加形式寫文件 FileWriter writer = new FileWriter(fileName, true ); writer.write(content); writer.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 修改文件名 * @param oldFilePath * @param newFileName */ public static void reNameLogFile(String oldFilePath,String newFileName){ File f= new File(oldFilePath); String c=f.getParent(); // File mm=new File(c + File.pathSeparator + newFileName + "_" + CommonUtil.getCurrTimeForString()); File mm= new File(c + "/" + newFileName + "_" + CommonUtil.getBeforeDateStr()); if (f.renameTo(mm)){ System.out.println( "修改文件名成功!" ); } else { System.out.println( "修改文件名失敗" ); } } public static void main(String[] args) { String fileName = "/Users/qin/Downloads/callLog.txt" ; String content = "new append!" ; FileWriterUtil.appendMethod(fileName, content); FileWriterUtil.appendMethod(fileName, "append end. \n" ); FileWriterUtil.reNameLogFile( "/Users/qin/Downloads/callLog.txt" , "rayda" ); } } |
Java PrintWriter&FileWriter 寫入追加到文件
用PrintWriter寫入文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import java.io.IOException; import java.io.PrintWriter; public class PrintWriteDemo { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter( "01.txt" ); out.print( "the quick brown fox" ); out.println( " jumps over the lazy dog." ); out.write( "work is like a capricious lover whose " ); out.write( "incessant demands are resented but who is missed terribly when she is not there\n" ); out.close(); //如果不關(guān)閉文件,文件停留在buffer zone, 不會(huì)寫進(jìn)"01.txt"中 } } |
FileWriter只能寫入文件,無法往文件中追加內(nèi)容
用FileWriter寫入和追加文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import java.io.IOException; import java.io.FileWriter; public class FileWriterDemo { public static void main(String[] args) throws IOException { FileWriter out = new FileWriter( "02.txt" ); //constructor中添加true,即FileWriter out = new FileWriter("02.txt", true)就是往02.txt中追加文件了 out.write( "work is like a capricious lover whose " ); out.write( "incessant demands are resented but who is missed terribly when she is not there\n" ); out.write( 98.7 + "\n" ); out.close(); //很重要,一定記得關(guān)閉文件 } } |
都別忘記 throws IOException
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/u014481096/article/details/53489364