Html 文件代码示例:
<HTML>
<HEAD>
<TITLE>REPORT</TITLE></HEAD>
<BODY>
<TITLE>REPORT</TITLE><PRE><H2>################ REPORT ###################</H2><H3>Setup</H3> Item1 1120 <br> Item2 Copy free <br> Item3 8/3/2017 5:44:51 AM <br> Item4 <Press OK> <br>
我需要阅读的信息是带有<br>
. 目标是将这些信息保存到如下所示的 excel 文件中
我目前使用 BufferedReader 读取 html 文件,但我不知道如何分隔包含字段和值的行。我试图使用 hashmap 来保存其字段名称和值,但我无法以正确的方式获取该值。我也尝试过 Jsoup 来摆脱 HTML 标签,但它让我更复杂地阅读自 html 文件以来的行
private final String[] modStrings = new String[]{"Item1", "Item2", "Item3", "Item4", "Item5"};
public void readHtmlFile() throws IOException {
FileReader reader = new FileReader("C:\\Users\\file.html");
// StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(reader);
String line;
String[] tempContent = {};
ArrayList content = new ArrayList();
HashMap modMap = new HashMap<>();
while ( (line=br.readLine()) != null) {
tempContent = line.split("<br>");
for(int i = 0; i < tempContent.length; i++){
for (String sub:modStrings){
if(tempContent[i].contains(sub)){
String value = "TODO HERE"; // TODO
content.add(sub);
modMap.put(sub, value);
}
}
}
}
// String textOnly = Jsoup.parse(sb.toString()).text();
for(int i = 0; i < content.size(); i++){
System.out.println(content.get(i));
System.out.println(modMap);
}
}
任何建议或想法都会有很大帮助。
给你的解决办法很简单,只需要使用String
class的util函数,根据你的html内容,使用合适的方法获取你想要的内容。例如,我在这里使用split(String regex)
[ split(String regex, int limit)](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)),
trim or
subString`... 做一个简单的技巧
示例代码:
public static void main(String[] args) throws IOException {
String[] modStrings = new String[] { "Item1", "Item2", "Item3", "Item4", "Item5" };
FileReader reader = new FileReader("html.html");
BufferedReader br = new BufferedReader(reader);
String line;
String[] tempContent = {};
ArrayList content = new ArrayList();
HashMap<String, String> modMap = new HashMap<>();
while ((line = br.readLine()) != null) {
if (line.contains("<br>")) {
line = line.substring(line.indexOf("Item1"));
tempContent = line.split("<br>");
for (String item : tempContent) {
if (item.contains("Item")) {
String[] itemArr = item.trim().split(" ", 2);
String itemName = itemArr[0].trim();
String value = itemArr[1].trim();
modMap.put(itemName, value);
}
}
}
}
for(String key : modMap.keySet()){
System.out.println(key + ":" + modMap.get(key));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句