如何使用Java替换目录中的多个HTML标题?

时间:2014-05-14 21:43:48

标签: java html tags

我正在创建一个Java应用程序来替换HTML文件的标题。我有一个HTML文件的文件夹,我想更改标题,我不想手动执行每个HTML文件。我想阅读HTML,找到标题标签(即<title>Some Title Here</title>),并将其替换为文件夹中每个HTML文件中的新标题(即<title>Some New Title Here</title>)。

可以使用java完成吗?怎么样?

继续获取IO例外

for (int i = 0; i < listOfFiles.length; i++) {
    if (listOfFiles[i].isFile()) {
        File file = new File(listOfFiles[i].getName());
        BufferedReader in = new BufferedReader(new FileReader(file));
        String line = in.readLine();
        while (line != null) {
            if (line.contains(type)) {
                line = line.replaceAll(
                        "(<title>[A-Za-z0-9\\s]+</title>)",
                        "<title>New title</title>");
            }

            lines.add(line);
            line = in.readLine();
        }
        in.close();

        PrintWriter out = new PrintWriter(listOfFiles[i]);
        for (String l : lines)
            out.println(l);
        out.close();

        System.out.println("File " + listOfFiles[i].getName());
    } else if (listOfF`enter code here`iles[i].isDirectory()) {
        System.out.println("Directory " + listOfFiles[i].getName());
    }

1 个答案:

答案 0 :(得分:1)

您可以阅读每个文件的内容并使用正则表达式替换标题,如下所示:

package replacetitle;

import java.io.*;
import java.util.*;

public class ReplaceTitle {
    public static void main(String[] args) {
        try {
            File file = new File("c:\\demo.html");
            replaceSelected(file, "<title>");
        } catch(IOException ex) {
            System.out.println(ex.toString());
        }
    }

    public static void replaceSelected(File file, String type) throws IOException {
        // we need to store all the lines
        List<String> lines = new ArrayList<String>();

        // first, read the file and store the changes
        BufferedReader in = new BufferedReader(new FileReader(file));
        String line = in.readLine();
        while (line != null) {
            if(line.contains(type)) {
                line = line.replaceAll("(<title>[A-Za-z0-9\\s]+</title>)","<title>New title</title>");
            }

            lines.add(line);
            line = in.readLine();
        }
        in.close();

        // now, write the file again with the changes
        PrintWriter out = new PrintWriter(file);
        for (String l : lines)
            out.println(l);
        out.close();
    }
}

然后保存文件。

希望有所帮助。

基于this问题。