fileInputStream.available()可以代替什么?
What can be replaced by fileInputStream.available()?
在学习JavaIO的时候,发现fileInputStream
有一个availabl()
的方法,读取本地文件时可以等于文件大小。那么如果能直接知道文件的大小,那么在需要读取整个文件的情况下,有必要用BufferedInputStream
修饰一下吗?
像这样:
FileInputStream fileInputStream=new FileInputStream("F:\test.txt");
byte[] data=new byte[fileInputStream.available()];
if (fileInputStream.read(data)!=-1) {
System.out.println(new String(data));
}
或
BufferedReader bufferedReader=new BufferedReader(new
FileReader("F:\test.txt"));
StringBuilder stringBuilder=new StringBuilder();
for (String line;(line=bufferedReader.readLine())!=null;){
stringBuilder.append(line);
}
System.out.println(stringBuilder.toString());
或
BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream("F:\test.txt"));
byte[] data=new byte[bufferedInputStream.available()];
if (bufferedInputStream.read(data)!=-1) {
System.out.println(new String(data));
}
这些方法的优缺点是什么?哪一个更好?
谢谢
你对available()
的意思理解有误。它 returns 您可以读取的可能字节数 而不会阻塞。 来自文档:
Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not. It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.
所以,如果你想将流转换为字节数组,你应该使用相应的库,例如IOUtils:
byte[] out = IOUtils.toByteArray(stream);
在学习JavaIO的时候,发现fileInputStream
有一个availabl()
的方法,读取本地文件时可以等于文件大小。那么如果能直接知道文件的大小,那么在需要读取整个文件的情况下,有必要用BufferedInputStream
修饰一下吗?
像这样:
FileInputStream fileInputStream=new FileInputStream("F:\test.txt");
byte[] data=new byte[fileInputStream.available()];
if (fileInputStream.read(data)!=-1) {
System.out.println(new String(data));
}
或
BufferedReader bufferedReader=new BufferedReader(new
FileReader("F:\test.txt"));
StringBuilder stringBuilder=new StringBuilder();
for (String line;(line=bufferedReader.readLine())!=null;){
stringBuilder.append(line);
}
System.out.println(stringBuilder.toString());
或
BufferedInputStream bufferedInputStream=new BufferedInputStream(new FileInputStream("F:\test.txt"));
byte[] data=new byte[bufferedInputStream.available()];
if (bufferedInputStream.read(data)!=-1) {
System.out.println(new String(data));
}
这些方法的优缺点是什么?哪一个更好? 谢谢
你对available()
的意思理解有误。它 returns 您可以读取的可能字节数 而不会阻塞。 来自文档:
Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not. It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream.
所以,如果你想将流转换为字节数组,你应该使用相应的库,例如IOUtils:
byte[] out = IOUtils.toByteArray(stream);