我必須讀取一個文本文件放入控制檯,然後寫回它。我能夠將文件讀取到控制檯,但是當我回寫並嘗試下次閱讀時,該文件是空的。誰能告訴我我在哪裏犯錯?Java寫入文本文件
這裏是代碼讀取原稿文件
public static ArrayList<Sales> readSaleData(ArrayList<Sales> sale) {
System.out.println();
ArrayList<Sales> sales = new ArrayList<Sales>();
Frame f = new Frame();
FileDialog saveBox = new FileDialog(f, "Reading text file", FileDialog.LOAD);
saveBox.setVisible(true);
String salePrice = saveBox.getFile();
String fileSavePlace = saveBox.getDirectory();
File inFile = new File(fileSavePlace + salePrice);
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(inFile));
String line;
int weekCount = 0;
while (((line = in.readLine()) != null)) {
weekCount++;
System.out.println("Week " + weekCount + "\t$" + line.replace(",", " $"));
String[] saleData = line.split(",");
for (String data : saleData) {
double price = Double.parseDouble(data);
Sales s = new Sales(price);
sales.add(s);
}
}
} catch (IOException io) {
System.out.println("There Was An Error Reading The File");
io.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
return sales;
}
這裏是代碼適用於寫要在此基礎上的文本文件
public static void writeSaleToTextFile(ArrayList<Sales> s) {
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Saving invoice information", FileDialog.SAVE);
foBox.setVisible(true);
String saleName = foBox.getFile();
String dirPath = foBox.getDirectory();
File outFile = new File(dirPath + saleName);
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(outFile)));
System.out.println("Going in");
for (int i = 0; i < s.size(); i++) {
Sales sale = s.get(i);
out.println(sale.toString());
System.out.println("This is the file size" + sale);
}
System.out.println("Coming Out");
}
catch (IOException io) {
System.out.println("An IO Exception occurred");
io.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
}
}
}
你得到任何輸出控制檯在寫入該文件?我的意思是,你的方法中有一些'System.out.println'調用。你得到了什麼? – Seelenvirtuose
你沒有調用flush方法。試試吧,讓我們知道。 –
@GD_Java - 但他是<<調用'close()'這將做一個刷新。 –