如何在文本文件中追加現有行?如果要編輯的行位於文件的中間怎麼辦?根據以下代碼,請提供建議。如何在文本文件中追加現有行
必須通過&去嘗試了以下內容:
- How to add a new line of text to an existing file in Java?
- How to append existing line within a java text file
我的代碼:
filePath = new File("").getAbsolutePath();
BufferedReader reader = new BufferedReader(new FileReader(filePath + "/src/DBTextFiles/Customer.txt"));
try
{
String line = null;
while ((line = reader.readLine()) != null)
{
if (!(line.startsWith("*")))
{
//System.out.println(line);
//check if target customer exists, via 2 fields - customer name, contact number
if ((line.equals(customername)) && (reader.readLine().equals(String.valueOf(customermobilenumber))))
{
System.out.println ("\nWelcome (Existing User) " + line + "!");
//w target customer, alter total number of bookings @ 5th line of 'Customer.txt', by reading lines sequentially
reader.readLine();
reader.readLine();
int total_no_of_bookings = Integer.valueOf(reader.readLine());
System.out.println (total_no_of_bookings);
reader.close();
valid = true;
//append total number of bookings (5th line) of target customer @ 'Customer.txt'
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filePath + "/src/DBTextFiles/Customer.txt")));
writer.write(total_no_of_bookings + 1);
//writer.write("\n");
writer.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
//finally
// {
//writer.close();
//}
}
}
}
readline()是故意讓我到達所需的路線。至於實現,我該如何重寫文本文件並寫下剩餘的內容?請舉例嗎?或者這適用? - http://www.raghuwansh.com/2013/07/10/write-text-file-in-java/ – user2945412
你可以使用BufferedWriter – grimrader22
檢查我的編輯。這有幫助嗎? – grimrader22