4 回答
TA貢獻1777條經驗 獲得超3個贊
你這樣做是為了記錄目的嗎?如果是這樣,那么有幾個庫。最受歡迎的兩個是Log4j和Logback。
Java 7+
如果您只需要執行此操作,則Files類可以輕松實現:
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);}catch (IOException e) {
//exception handling left as an exercise for the reader}小心:NoSuchFileException如果文件尚不存在,上述方法將拋出一個。它也不會自動附加換行符(當您追加到文本文件時通常需要它)。Steve Chambers的答案涵蓋了如何在Files課堂上做到這一點。
但是,如果您要多次寫入同一文件,則必須多次打開和關閉磁盤上的文件,這是一個很慢的操作。在這種情況下,緩沖編寫器更好:
try(FileWriter fw = new FileWriter("myfile.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)){
out.println("the text");
//more code
out.println("more text");
//more code} catch (IOException e) {
//exception handling left as an exercise for the reader}筆記:
FileWriter構造函數的第二個參數將告訴它附加到文件,而不是寫一個新文件。(如果該文件不存在,則會創建該文件。)BufferedWriter對于昂貴的作家(例如FileWriter),建議使用a 。使用a
PrintWriter可以訪問println您可能習慣的語法System.out。但
BufferedWriter和PrintWriter包裝是不是絕對必要的。
舊Java
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("the text");
out.close();} catch (IOException e) {
//exception handling left as an exercise for the reader}異常處理
如果您需要針對較舊的Java進行強大的異常處理,那么它會非常冗長:
FileWriter fw = null;BufferedWriter bw = null;PrintWriter out = null;try {
fw = new FileWriter("myfile.txt", true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
out.println("the text");
out.close();} catch (IOException e) {
//exception handling left as an exercise for the reader}finally {
try {
if(out != null)
out.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
try {
if(fw != null)
fw.close();
} catch (IOException e) {
//exception handling left as an exercise for the reader
}}TA貢獻1848條經驗 獲得超6個贊
不應該使用try / catch塊的所有答案都包含finally塊中的.close()塊嗎?
標記答案的示例:
PrintWriter out = null;try {
out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
out.println("the text");} catch (IOException e) {
System.err.println(e);} finally {
if (out != null) {
out.close();
}}此外,從Java 7開始,您可以使用try-with-resources語句。關閉聲明的資源不需要finally塊,因為它是自動處理的,并且也不那么詳細:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
out.println("the text");} catch (IOException e) {
System.err.println(e);}TA貢獻1725條經驗 獲得超8個贊
為了略微擴展Kip的答案,這里有一個簡單的Java 7+方法,可以將新行附加到文件中,如果它尚不存在則創建它:
try {
final Path path = Paths.get("path/to/filename.txt");
Files.write(path, Arrays.asList("New line to append"), StandardCharsets.UTF_8,
Files.exists(path) ? StandardOpenOption.APPEND : StandardOpenOption.CREATE);} catch (final IOException ioe) {
// Add your own exception handling...}注意:上面使用了Files.write將文本行寫入文件的重載(即類似于println命令)。要將文本寫到最后(即類似于print命令),Files.write可以使用替代重載,傳入字節數組(例如"mytext".getBytes(StandardCharsets.UTF_8))。
添加回答
舉報
