[英]How to “”save" the result in a text file in java
我想將輸出結果保存到文本文件中,並在需要時檢索它。 為了將輸出寫入.txt,我使用了以下代碼。
import java.io.*;
class FileOutputDemo {
public static void main(String args[])
{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
// Create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("myfile.txt");
// Connect print stream to the output stream
p = new PrintStream( out );
p.append ("This is written to a file");
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}
}
它工作正常,並且已寫入預期的文本文件。 但是,每當我重新編譯程序時,都會寫入新的輸出,而刪除先前的輸出。 有沒有一種方法可以保存先前寫入的文件的輸出,並從先前保留的文本文件(重新編譯后)的位置進行提取。
參見new FileOutputStream(file, true);
(或fileName
作為名稱而不是file
對象),如該類的構造函數中所記錄。
更改:
catch (Exception e)
{
System.err.println ("Error writing to file");
}
至:
catch (Exception e)
{
e.printStackTrace();
}
后者以較少的鍵入提供了更多信息。
如果這個程序。 如果要具有GUI,則通常由用戶在JTextArea
輸入文本。 該組件是從JTextComponent
擴展而來的,它提供了幾乎一個“一線式”來保存和加載文本:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.