在java中不使用循环读取完整文件 [英] read complete file without using loop in java
本文介绍了在java中不使用循环读取完整文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
如何从文件内容
Java 中将整个文本文件转换为字符串
我正在尝试使用 FileReader 读取文件的内容.但我想在不逐行读取的情况下读取文件.是否可以在没有循环的情况下读取整个文件.我正在使用以下代码
I am trying to read the contents of a file using FileReader . But i want to read the file without reading a line by line . Is it possible to read the whole file without loop. I am using the following code
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();
}
推荐答案
如果文件小,可以一次读取整个数据:
If the file is small, you can read the whole data once:
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");
这篇关于在java中不使用循环读取完整文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文