可能重复:
如何从文件内容创建Java String
我有一个html文件,我想用它来提取信息.为此,我正在使用Jsoup.现在使用Jsoup,我需要将html文件转换为字符串.我怎样才能做到这一点?
File myhtml = new File("D:\\path\\report.html")';
Run Code Online (Sandbox Code Playgroud)
现在,我想要一个包含html文件内容的String对象.
gig*_*dot 30
我使用apache common IO将文本文件读入单个字符串
String str = FileUtils.readFileToString(file);
Run Code Online (Sandbox Code Playgroud)
简单而"干净".你甚至可以毫无困难地设置文本文件的编码.
String str = FileUtils.readFileToString(file, "UTF-8");
Run Code Online (Sandbox Code Playgroud)
Sea*_*oyd 13
使用像Guava或Commons/IO这样的库.他们有oneliner方法.
番石榴:
Files.toString(file, charset);
Run Code Online (Sandbox Code Playgroud)
Commons/IO:
FileUtils.readFileToString(file, charset);
Run Code Online (Sandbox Code Playgroud)
没有这样的库,我会编写一个帮助方法,如下所示:
public String readFile(File file, Charset charset) throws IOException {
return new String(Files.readAllBytes(file.toPath()), charset);
}
Run Code Online (Sandbox Code Playgroud)
使用Java 7,它很简单:
final String EoL = System.getProperty("line.separator");
List<String> 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();
Run Code Online (Sandbox Code Playgroud)
但是,它确实有一些小的警告(比如处理不适合内存的文件).
我建议你看看官方Java教程中的相应部分(如果你有一个以前的Java,那也是如此).
正如其他人所指出的,你可能会发现sime第三方库很有用(比如Apache commons I/O或Guava).
| 归档时间: |
|
| 查看次数: |
102500 次 |
| 最近记录: |