2017-08-29 149 views
1

我試圖創建一種方法從我的txt文件中刪除一些文本。我開始通過檢查該文件中存在的字符串,我有:從文本文件中刪除多行

public boolean ifConfigurationExists(String pathofFile, String configurationString) 
    { 
     Scanner scanner=new Scanner(pathofFile); 
     List<String> list=new ArrayList<>(); 

     while(scanner.hasNextLine()) 
     { 
      list.add(scanner.nextLine()); 
     } 

     if(list.contains(configurationString)) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 

因爲我想要刪除的字符串中包含多行(字符串configurationString =「這是\ n一個\ n多行\ n串」; )我開始創建一個新的字符串數組,並將字符串拆分爲數組成員。

public boolean deleteCurrentConfiguration(String pathofFile, String configurationString) 
{ 
    String textStr[] = configurationString.split("\\r\\n|\\n|\\r"); 

    File inputFile = new File(pathofFile); 
    File tempFile = new File("myTempFile.txt"); 

    BufferedReader reader = new BufferedReader(new FileReader(inputFile)); 
    BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile)); 

    String currentLine; 

    while((currentLine = reader.readLine()) != null) { 
     // trim newline when comparing with lineToRemove 
     String trimmedLine = currentLine.trim(); 
     if(trimmedLine.equals(textStr[0])) continue; 
     writer.write(currentLine + System.getProperty("line.separator")); 
    } 

    writer.close(); 
    reader.close(); 
    boolean successful = tempFile.renameTo(inputFile); 

    return true; 
} 

可有人請就如何從txt文件中刪除字符串之前和之後的字符串和幫助也行?

+5

一個不會「刪除文件中的行」。唯一的可能性是複製文件,並且在複製文件時不寫出不需要的行。 –

+0

你當然可以刪除一部分字符串,但像吉姆我建議不要直接使用該文件。無論如何,掃描儀無法直接寫入您處於只讀模式的文件。您可以使用java.lang.String中的替換或子字符串方法從原始文件中獲取內容並將其寫入新文件中 –

+0

是的我正在做這樣的事情: – ToniT

回答

0

有很多不同的方法可以做到這一點,雖然我這樣做的一種方式是首先將文件內容逐行讀入字符串數組(看起來像您已經這樣做了),然後刪除數據,不需要,並逐行寫入您想要的新信息。

要你不想行,你不希望前行刪除線,以後你行不想要的,你可以是這樣的:

List<String> newLines=new ArrayList<>(); 
boolean lineRemoved = false; 
for (int i=0, i < lines.length; i++) { 
    if (i < lines.length-1 && lines.get(i+1).equals(lineToRemove)) { 
    // this is the line before it 
    } else if (lines.get(i).equals(lineToRemove)) { 
    // this is the line itself 
    lineRemoved = true; 
    } else if (lineRemoved == true) { 
    // this is the line after the line you want to remove 
    lineRemoved = false; // set back to false so you don't remove every line after the one you want 
    } else 
    newLines.add(lines.get(i)); 
} 
// now write newLines to file 

注意,這代碼很粗糙,未經測試,但應該讓你到達需要的地方。

+0

問題是我有一個包含四行的字符串在它和我必須刪除這些行之前的行和這些行之後的行 – ToniT

+0

因此,你只需要剩餘的4行,你在內存中? –

+0

即說這是file.txt的: 一個 b Ç d Ë ˚F 克 ħ 的myString = 「C \ ND \ NE \ NF」 運行方法,file.txt的後欲be: a h – ToniT