[英]Writing to a new line in a .csv file without overwriting the first line
我正在嘗試這樣做,以便每當用戶輸入名稱並將其傳遞時,都會將該信息(以名稱,傳遞的格式)寫入到位置指定的.csv文件中。 但是,每當我運行該程序時,它都會覆蓋第一行。 我嘗試添加"\\n"
和out.newLine();
但由於某種原因,它不會寫入下一行。 我不知道為什么要這么做,所以我希望有人知道為什么。
public class TestClass {
public static void main(String[] args) throws IOException {
String location = "my location to the file (.csv)";
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
String name = sc.next();
System.out.print("Pass: ");
String pass = sc.next();
BufferedWriter out = new BufferedWriter(new FileWriter(location));
out.write(name + "," + pass + "\n");
out.newLine();
out.close();
}
}
當前在文件中我有這個:
測試,一個
當我運行程序時:
name: one
pass: two
退出程序並檢查文件,第一行被替換為一,二,而不是像這樣:
test, one
one, two
謝謝您的幫助:)
使用FileWriter
的第二個構造函數:
FileWriter(字符串fileName,布爾值附加)
fileName-字符串與系統有關的文件名。
append-布爾值(如果為true),則數據將被寫入文件的末尾而不是開始。
BufferedWriter out = new BufferedWriter(new FileWriter(location, true));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.