今天晚上用FileInputStream练习的时候怎么也读取不出来文件中的内容,找了半天,终于找到问题所在(赶紧记下来,下次不能再犯)!
public static void readTest2() {
File file = new File("f:/aaa/a.txt");
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
// 4. 准备一个8KB字节缓冲数组
byte[] buf = new byte[1024 * 8];
int length = -1;
// 5. 读取数据
while ((length = fileInputStream.read(buf)) != -1) {
System.out.println(new String(buf, 0, length));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != fileInputStream) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
上面是方法的源代码,下面调用一下:
public class Demo {
public static void main(String[] args){
readTest2();
}
}
正常情况下应该输出f:/aaa/a.txt 这个文件中的内容,但是我运行了好几遍没有结果
下面是我的a.txt中的内容(内容过多,就截图看一下):
看到这里想必知道的就能看出来哪里出问题了,我的文件中的内容没有任何分隔符,全程一句下来,我定义的缓冲数组根本放不下,导致结果出不来!!!
使用FileInputStream文件操作输入字节流时,定义的缓冲数组如果容量如果小于文件中某一串内容时,就会读取失败
文章内容如果有什么问题,欢迎在下面评论指出-_-