簡體   English   中英

從.txt文件刪除行

[英]Deleting lines from a .txt file

因此,我有一個程序可以為您保存密碼和用戶名,然后將其保存為.txt文件。 我添加了一個選項,以防萬一您拼錯了某些內容而刪除其中一項。 這就是我的文本文件的樣子。

Website
Username
Password

anotherWebsite
anotherUsername
anotherPassword

現在,密碼沒有加密,因為我被指示不要加密密碼。

我的主要問題是,您是否可以在不讀取整個文件的情況下刪除文本文件中的某些行,然后將所需的行保存到新文件中,然后再使用該行?

您的問題的答案是否定的。 本質上,執行此操作的方法是重寫文件,省略要刪除的行

您要做的是重寫整個文件,而不要寫您想跳過的行。

查找文件中的一行並刪除它對於您的情況似乎已經足夠好了,您只需檢查三件事(元組(網站,用戶名,密碼),而不是僅檢查一個參數即可。

public void removeLineFromFile(String file, String lineToRemove) {

try {

  File inFile = new File(file);

  if (!inFile.isFile()) {
    System.out.println("Parameter is not an existing file");
    return;
  }

  //Construct the new file that will later be renamed to the original filename.
  File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

  BufferedReader br = new BufferedReader(new FileReader(file));
  PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

  String line = null;

  //Read from the original file and write to the new
  //unless content matches data to be removed.
  while ((line = br.readLine()) != null) {

    if (!line.trim().equals(lineToRemove)) {

      pw.println(line);
      pw.flush();
    }
  }
  pw.close();
  br.close();

  //Delete the original file
  if (!inFile.delete()) {
    System.out.println("Could not delete file");
    return;
  }

  //Rename the new file to the filename the original file had.
  if (!tempFile.renameTo(inFile))
    System.out.println("Could not rename file");

}
catch (FileNotFoundException ex) {
  ex.printStackTrace();
}
catch (IOException ex) {
  ex.printStackTrace();
}

}

我不知道沒有另一個讀寫臨時文件的方法。 我認為這是不可能的,因為您將其讀取為字節數組並使用一些高級API。

如果您使用的是Java 8,我建議您使用以下結構:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

    public static void main(String[] args) throws IOException {
        String content = new String(Files.readAllBytes(Paths.get("duke.java")));
    }

然后,使用該字符串,您可以讀取,連接或刪除信息。

鏈接: http//www.adam-bien.com/roller/abien/entry/java_8_reading_a_file

如果您使用的是其他版本,請點擊以下鏈接:

在文件中找到一行並將其刪除

在文件中,信息的每一位都有一個位置。 刪除其中一些位不會移動其他元素的位置。

 File

 1111111111111111
 222222222.....22
 3333.33333.3.333
 44.444.444.444.4
 5555555555555555

 1111111111111111
 222222222.....22
 44.444.444.444.4
 5555555555555555

通過刪除

 3333.33333.3.333

和移動

 44.444.444.444.4
 5555555555555555

進入先前由

 3333.33333.3.333
 44.444.444.444.4

因此,您可以在沒有臨時文件的情況下進行操作,請使用以下技術進行購買

  1. 打開一個隨機訪問文件(我們將在其中進行跳轉。
  2. 讀取文件,直到您檢測到要刪除的項目,並在該區域的開始處保留一個“位置”。
  3. 計算已刪除區域的“大小”。
  4. 在刪除區域之外還有未被移動的區域
    1. 在刪除區域上復制該區域。
    2. 將刪除的區域重新分配到剛從中復制的區域。
  5. 寫入文件末尾。

當然,這確實非常危險。 因為該過程中的任何中斷都會使您得到的文件不是原始文件,也不是結果文件。 由於文件復制很容易因斷電,被殺死的程序等而中斷。您真的不希望這種方法,因為很難從故障中恢復。

這就是為什么編寫第二個文件,等到完成后再將其移到原始文件上的原因,這是一個更好的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM