2017-08-29 144 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