使用java替换文件中的String

时间:2014-03-25 17:10:58

标签: java file

我有一个TXT文件,我想在其中更改此字符串

<!DOCTYPE Publisher PUBLIC "-//Springer-Verlag//DTD A++ V2.4//EN" "http://devel.springer.de/A++/V2.4/DTD/A++V2.4.dtd">

使用Java进入此<!DOCTYPE Publisher>

我写了以下函数,但它似乎没有用。

public void replace() {

try {
    File file = new File("/home/zakaria/Bureau/PhD/test2/file.txt");
    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line = "", oldtext = "";
    while((line = reader.readLine()) != null) {
       oldtext += line + "\n";
    }
    reader.close();
    String newtext = oldtext
      .replaceAll("<!DOCTYPE Publisher\nPUBLIC \"-//Springer-Verlag//DTD A++ V2.4//EN\" \"http://devel.springer.de/A++/V2.4/DTD/A++V2.4.dtd\">", 
      "<!DOCTYPE Publisher>");

    FileWriter writer = new FileWriter("/home/zakaria/Bureau/PhD/test2/file.txt");
    writer.write(newtext);
    writer.close();

  } catch (IOException ioe) {
    ioe.printStackTrace();
  }
}

我做错了什么?

4 个答案:

答案 0 :(得分:1)

试试这个简单的代码:

public static void replace() {

    try {
        File file = new File("resources/abc.txt");
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = "", oldtext = "";
        boolean found = false;
        while ((line = reader.readLine()) != null) {
            if (line.trim().startsWith("<!DOCTYPE Publisher")) {
                found = true;
            }
            if (line.trim().endsWith("A++V2.4.dtd\">")) {
                oldtext += "<!DOCTYPE Publisher>";
                found = false;
                continue;
            }
            if (found) {
                continue;
            }
            oldtext += line + "\n";
        }
        reader.close();

        FileWriter writer = new FileWriter("resources/file.txt");
        writer.write(oldtext);
        writer.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

答案 1 :(得分:1)

你很幸运,因为它根本没有改变任何东西。

否则你丢失了原始文件......

永远不要修改文件!!

创建一个临时文件,您可以在其中编写修改后的内容,然后重命名为原始文件。

此外,您要替换的字符串非常复杂,并且您不想使用.replace(),因为这将替换所有出现的内容。

这样做:

final String quoted 
    = Pattern.quote("<!DOCTYPE Publisher\nPUBLIC \"-//Springer-Verlag//DTD A++ V2.4//EN\" \"http://devel.springer.de/A++/V2.4/DTD/A++V2.4.dtd\">");
final Pattern pattern = Pattern.compile(quoted);

final Path victim = Paths.get("/home/zakaria/Bureau/PhD/test2/file.txt");
final Path tmpfile = Files.createTempFile("tmp", "foo");

final byte[] content = Files.readAllBytes(victim);
final String s = new String(content, StandardCharsets.UTF_8);
final String replacement = pattern.matcher(s).replaceFirst("<!DOCTYPE Publisher>");

try (
    final OutputStream out = Files.newOutputStream(tmpfile);
) {
    out.write(replacement.getBytes(StandardCharsets.UTF_8));
    out.flush();
}
Files.move(tmpfile, victim);

答案 2 :(得分:1)

如果要消除的文本位于第二行和后续行,如在演示输入

<!DOCTYPE Publisher
PUBLIC "-//Springer-Verlag//DTD A++ V2.4//EN"     
"http://devel.springer.de/A++/V2.4/DTD/A++V2.4.dtd">

并且标记中第一个和最后一个之间没有行包含结束>,然后您可以执行以下操作:

while(more lines to process)
   if "<!DOCTYPE Publisher" is not found
      read line and output it
   else
      //This is the first line in a <!DOCTYPE tag
      read the line and output it, appending '>' to the end
      while the next line does NOT end with a '>'
         discard it (don't output it)

答案 3 :(得分:1)

试试这个正则表达式:

String newtext = oldtext.replaceAll(
       "<!DOCTYPE Publisher\nPUBLIC \"-\\/\\/Springer-Verlag\\/\\/DTD A[+][+] V2[.]4\\/\\/EN\"[ ]\"http:\\/\\/devel[.]springer[.]de\\/A[+][+]\\/V2[.]4\\/DTD\\/A[+][+]V2[.]4[.]dtd\">", "<!DOCTYPE Publisher>");

唯一的变化是逃避正斜杠,并在方括号之间加上点和加号。