[英]How to append existing line in 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();
//}
}
}
}
要將內容附加到現有文件,您需要以附加模式打開它。 例如,使用FileWriter(String fileName,boolean append)並將true
作為第二個參數傳遞。
如果該行位於中間,則需要將整個文件讀入內存,然后在完成所有編輯后將其寫回。
這對於小文件可能是可行的,但如果你的文件太大,那么我建議將實際內容和編輯后的內容寫入臨時文件,完成后刪除舊文件,將臨時文件重命名為同名舊的。
reader.readLine()方法每次調用時都會增加一行。 我不確定這是否適用於您的程序,但您可能希望將reader.readline()存儲為String,因此只調用一次。
要在文本文件的中間附加一行,我相信您必須重新編寫文本文件,直到您想要追加該行的位置,然后繼續寫入文件的其余部分。 這可以通過將整個文件存儲在String數組中,然后寫入某個點來實現。
寫作示例:
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
writer.write(someStuff);
writer.write("\n");
writer.close();
您可能應該遵循您發布的第二個鏈接的答案中的建議。 您可以使用隨機訪問文件訪問文件的中間位置,但如果您開始在文件中間的任意位置附加而不記錄開始編寫時的內容,則會覆蓋其當前內容,如這個答案 。 除非有問題的文件非常大,否則最好的辦法是使用現有文件和新數據組裝新文件,正如其他人之前所建議的那樣。
AFAIK你做不到。 我的意思是,附加一條線是可能的,但不能插入中間。 這與java或其他語言無關...文件是一個寫入字節的序列...如果你在一個任意點插入一些序列不再有效並需要重寫的東西。
所以基本上你必須創建一個函數來執行read-insert-slice-rewrite
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.