欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

批量改变HTML文件的meta信息中的编码方式

程序员文章站 2024-01-21 22:19:16
...
有的时候html文件的编码方式与meta信息中指定的编码方式不同,可以通过这段代码搞一下。 此程序依赖jsoup和commons-io包

  1. import java.io.File;
  2. import java.io.FileWriter;
  3. import java.io.IOException;
  4. import java.io.Writer;
  5. import java.util.Iterator;
  6. import org.apache.commons.io.FileUtils;
  7. import org.jsoup.Jsoup;
  8. import org.jsoup.nodes.Document;
  9. import org.jsoup.nodes.Element;
  10. import org.jsoup.select.Elements;
  11. public class main {
  12. /**
  13. * @param args
  14. * @throws IOException
  15. */
  16. public static void main(String[] args) throws IOException {
  17. // TODO Auto-generated method stub
  18. File input = new File("C:\\Users\\jack\\Desktop\\新建文件夹\\jdk-zh");
  19. Iterator it = FileUtils.iterateFiles(input, null, true);
  20. while (it.hasNext()) {
  21. File file = it.next();
  22. Document doc = Jsoup.parse(file, "gb2312");
  23. Elements content = doc.getElementsByAttributeValueStarting("content", "text/html;");
  24. for (Element meta : content) {
  25. meta.attr("content", "text/html; charset=utf-8");
  26. System.out
  27. .println("修改content--------" + file.getName() + "---");
  28. }
  29. FileUtils.writeStringToFile(file, doc.html(),"utf-8");
  30. }
  31. }
  32. }
复制代码