今天了解了一下fileinputstream的使用,关于其read方法的使用
1、如何使用fileinputstream读取文件中的内容,首先通过阅读源码来了解一下其原理
/**
* Reads a byte of data from this input stream. This method blocks
* if no input is yet available.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* file is reached.
* @exception IOException if an I/O error occurs.
* @Range(from=-1,to=255)
*/
public int read() throws IOException {
return read0();
}
Range(from=-1,to=255)
这是read()方法的说明,其读取的其实就是按照ACSII码来读取的,超出的部分就会显示乱码。并且返回值为数据的ACSII码,例如
pj.txt中
“
hello world
你好世界
”
import java.io.*;
import java.util.ArrayList;
public class E1 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream=new FileInputStream("C:\\Users\\hasee\\Desktop\\pj.txt");
int temp;
while((temp=fileInputStream.read())!=-1)
System.out.print((char)temp);
}
}
结果为
hello world
ä½ å¥½ä¸–ç•Œ
所以我们读取包括在ASCII中的数据的时候才使用这个方法,不然就选择fileinputstream中的read(byte[])方法。
源码如下
/**
* Reads up to <code>b.length</code> bytes of data from this input
* stream into an array of bytes. This method blocks until some input
* is available.
*
* @param b the buffer into which the data is read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the file has been reached.
* @exception IOException if an I/O error occurs.
* @Range(from=-1,to=java.lang.integer.MAX_VALUE)
*/
public int read(byte b[]) throws IOException {
return readBytes(b, 0, b.length);
}
由此可知,这个方法是把读取到的数据存在byte[]数组当中,并返回读取到的数据的长度,并且其数据范围
Range(from=-1,to=java.lang.integer.MAX_VALUE)
可以读取的范围更大。
同样使用pj.txt测试
import java.io.*;
import java.util.ArrayList;
public class E1 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream=new FileInputStream("C:\\Users\\hasee\\Desktop\\pj.txt");
byte[] bytes=new byte[1024];
while (fileInputStream.read(bytes)!=-1){
System.out.print(new String(bytes));
}
}
}
结果为
hello world
你好世界
注意:问题在今天使用read方法的时候出现,代码如下
import java.io.*;
import java.util.ArrayList;
public class E1 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream=new FileInputStream("C:\\Users\\hasee\\Desktop\\pj.txt");
while (fileInputStream.read()!=-1){
System.out.print((char)fileInputStream.read());
}
}
}
测试文件中内容为
“123456”
运行结果如下
246
我一开始很疑惑,为什么总是缺少135,后面了解到,read方法其实可以理解为一个指针,当他第一次调用时候就会指向第一个数据,而后每一次调用都会使得指针往后移动一位,而我的代码中使用了read()方法在while中进行了判断,然后又进行了输出,导致判断的那一次指向的数据就没有被输出,所就会产生这种情况。