可能重复:
How to create a Java String from the contents of a file
我遇到了将整个文件(.html文件)加载到单个字符串的问题。
我正在尝试打印<body>
和</body>
之间的内容。然而;当我运行我的代码时,它无法在输入文件中写入任何内容。我相信问题是我的第一行没有<body>
或</body>
标签,这意味着indexOf()方法将返回-1,因此整个问题无法实现。有人告诉我应该加载整个.html,其中包含很多行到一个字符串,我相信他的意思是加载一行。我不知道怎么做......
这是我的代码:
PrintWriter pr;
try{
c = new Scanner(f);
pr = new PrintWriter(new FileOutputStream(o));
while (c.hasNextLine()){
String text = c.nextLine();
String index = "<body>";
String index2 = "</body>";
int i1 = text.indexOf(index);
int i2 = text.indexOf(index2);
text = text.substring(i1+6,i2);
System.out.println("here it is");
pr.println(text);
System.out.println("you did !!!");
pr.flush();}
}catch(Exception e){}
}
答案 0 :(得分:0)
确定。这是一个小样本,可以帮助您入手。
这将是一个简单的HTML页面 但是对于复杂的页面(带有嵌入式CSS等),你必须弄清楚如何找到正文的开始/结束。
FileInputStream fin = new FileInputStream("theFile.html");
byte[] data = new byte[fin.available()];
fin.read(data);
String htmlFile = new String(data);
int start = htmlFile.indexOf("<body>");
if(start != -1){
int end = html.indexOf("</body");
if(end != -1){
System.out.println("Body is: html.substring(start + 6, end));
}
}