[英]How to write a new line to a file in Java?
我正在使用PrintWriter
類將新行寫入文件。 它按預期方式寫入行,但是當我要寫入新數據時,它將覆蓋舊數據,而不是寫入新行。 這是我到目前為止所擁有的。
import javax.swing.*;
import java.text.*;
import java.util.*;
import java.io.*;
public class TimeTracker
{
/**
* @param args the command line arguments
* @throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException
{
DecimalFormat money = new DecimalFormat("$#,##0.00");
PrintWriter toFile = new PrintWriter("timeWorked.dat");
Scanner readFile = new Scanner(new FileReader("timeWorked.dat"));
String client = JOptionPane.showInputDialog("Client's Name");
int rate = Integer.parseInt(JOptionPane.showInputDialog("Rate per hour?"));
String output;
output = "Client's Name: " + client +
" Pay rate agreed: " + money.format(rate) + " per hour";
toFile.append(output);
toFile.flush();
if (readFile.hasNext())
{
toFile.append("\n");
toFile.write(output);
toFile.flush();
}
JOptionPane.showMessageDialog(null, readFile.nextLine());
}
}
通過閱讀PrintWriter
的javadoc ,您可以了解到,在創建一個以文件名作為構造函數參數的實例時,該文件(如果存在)將被截斷為零大小。
相反,您可以使用FileWriter 。 在這里查看示例。 並且不要錯過使用帶有boolean參數的重載構造函數,例如new FileWriter("timeWorked.dat", true)
,它會打開文件進行附加。
從PrintWriter的javadoc中:
參數:fileName用作此編寫器目標的文件名。 如果文件存在,那么它將被截斷為零大小; 否則,將創建一個新文件。 輸出將被寫入文件並被緩沖。
我想這就是問題:)
要解決您的問題,請使用類FileWriter,如下所示:
new FileWriter("timeWorked.dat", true)
布爾參數true告訴FileWriter打開要附加的文件。 這意味着您寫入文件的數據將在最后添加。
這對我有用:
File file = new File("output.txt");
FileOutputStream outputStream = new FileOutputStream(file, false);
PrintWriter out = new PrintWriter(outputStream, true);
out.println("test");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.