Java InputStream如何读取文件呢?
下文笔者将讲述InputStream读取文件的方法分享,如下所示:
FileInputStream通过文件byte数组暂存文件中内容
使用InputStream从文件里读取数据
FileInputStream通过文件byte数组暂存文件中内容
将其转换为String数据
再根据“回车换行” 进行分割
public static String[] readToString(String filePath) {
File file = new File(filePath);
Long filelength = file.length(); // 获取文件长度
byte[] filecontent = new byte[filelength.intValue()];
try {
FileInputStream in =new FileInputStream(file); in .read(filecontent); in .close();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
String[] fileContentArr = new String(filecontent).split("\r\n");
return fileContentArr; // 返回文件内容,默认编码
}
使用InputStream从文件里读取数据,在已知文件大小的情况下,建立合适的存储字节数组
public class TestClass {
public static void main(String args[]) throws Exception {
File f = new File("E:" + File.separator + "test" + File.separator + "StreamDemo" + File.separator + "java265.txt");
InputStream in =new FileInputStream(f);
byte b[] = new byte[(int) f.length()]; //创建合适文件大小的数组
in .read(b); //读取文件里的内容到b[]数组
in .close();
System.out.println(new String(b));
}
}
使用InputStream从文件里读取数据
当不知道文件大小时,可循环读取文件
public static void main(String args[]) throws Exception {
File f = new File("E:" + File.separator + "test" + File.separator + "StreamDemo" + File.separator + "java265.txt");
InputStream in =new FileInputStream(f);
byte b[] = new byte[1024];
int len = 0;
int temp = 0; //全部读取的内容都使用temp接收
while ((temp = in.read()) != -1) { //当没有读取完时,继续读取
b[len] = (byte) temp;
len++;
} in .close();
System.out.println(new String(b, 0, len));
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


