可能重复:
How to create a Java String from the contents of a file
Whole text file to a String in Java
我正在尝试使用FileReader读取文件的内容。但是我想读取文件,而不是逐行读取。是否有可能在没有循环的情况下读取整个文件。我正在使用下面的代码
try
{
File ff=new File("abc.txt");
FileReader fr=new FileReader(ff);
String s;
while(br.read()!=-1)
{
s=br.readLine();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
发布于 2013-01-05 15:40:03
如果文件是small,则可以一次读取整个数据:
File file = new File("a.txt");
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
String str = new String(data, "UTF-8");
发布于 2013-01-05 15:36:07
Java 7单行解决方案
List<String> lines = Files.readAllLines(Paths.get("file"), StandardCharsets.UTF_8);
或
String text = new String(Files.readAllBytes(Paths.get("file")), StandardCharsets.UTF_8);
https://stackoverflow.com/questions/14169661
复制相似问题