我正在使用PrintWriter
類將新行寫入文件。它按預期寫入行,但是當我想寫新數據時,它會寫入舊數據而不是寫新行。這是我到目前爲止。如何在Java中將新行寫入文件?
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());
}
}
你正在閱讀和寫作的同時同一個文件?故意地? – dcsohl
是的,我做了readFile來檢查文件是否有一行,如果它比我想它寫一個新行,而不寫過去的行,但不能讓它工作。 –