本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
How to create a Java String from the contents of a file
我有一个HTML文件,我想用它来提取信息。为此,我使用的是JSoup。现在,为了使用JSoup,我需要将HTML文件转换成一个字符串。我该怎么做?
File myhtml = new File("D:\\path\
eport.html")';
现在,我想要一个字符串对象,它包含HTML文件中的内容。
检查:stackoverflow.com/questions/326390/…
逐字符读取文件,并将每个字符放入StringBuffer。完成后,向StringBuffer请求字符串。
检查jsoup api。它使用parse方法来获取文件。您不需要手动读取文件内容。
我使用apache common io将文本文件读取为单个字符串
String str = FileUtils.readFileToString(file);
简单和"干净"。甚至可以轻松设置文本文件的编码。
String str = FileUtils.readFileToString(file,"UTF-8");
你会怎么做呢?读取字符串文件
是否将字符串写入文件?
附加链接已过期,请发布最新的URL好吗?
使用像guava或commons/io这样的库。他们有一套方法。
番石榴:
Files.toString(file, charset);
共享空间/IO:
FileUtils.readFileToString(file, charset);
如果没有这样的库,我会编写一个助手方法,如下所示:
public String readFile(File file, Charset charset) throws IOException {
return new String(Files.readAllBytes(file.toPath()), charset);
}
用Java 7,它是简单的:
final String EoL = System.getProperty("line.separator");
List lines = Files.readAllLines(Paths.get(fileName),
Charset.defaultCharset());
StringBuilder sb = new StringBuilder();
for (String line : lines) {
sb.append(line).append(EoL);
}
final String content = sb.toString();
但是,它确实有一些小警告(比如处理不适合内存的文件)。
我建议在官方Java教程中查看相应的部分(如果你有一个Java),这也是一个例子。
正如其他人指出的,您可能会发现SIME第三方库很有用(比如ApacheCommonsI/O或Guava)。
用文件inputstream读取文件并将文件内容附加到字符串。
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class CopyOffileInputStream {
public static void main(String[] args) {
//File file = new File("./store/robots.txt");
File file = new File("swingloggingsscce.log");
FileInputStream fis = null;
String str ="";
try {
fis = new FileInputStream(file);
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
str += (char) content;
}
System.out.println("After reading file");
System.out.println(str);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
顺便说一下,Jsoup有一个方法:http://jjang.org/APIDOCS/org/jTous/jPosith.html ypARPARSE(java. IO文件,%20java.
您可以将myhtml的所有内容复制到String中,如下所示:
Scanner myScanner = null;
try
{
myScanner = new Scanner(myhtml);
String contents = myScanner.useDelimiter("\\Z").next();
}
finally
{
if(myScanner != null)
{
myScanner.close();
}
}
当然,您可以添加一个catch块来正确处理异常。
为什么不逐行读取文件并将其添加到StringBuffer?
到达文件结尾后,可以从StringBuffer获取字符串。