1.构造输入流,读取一个字节
read();从输入流中读取数据的下一个字节,返回的是一个int类型的值
public void testFileInputStream() {
FileInputStream input =null;
try {
input = new FileInputStream("Test/demo02.txt");
int a = input.read();
System.out.println((char)a);
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(input!=null)
input.close();//关闭输入流,释放资源
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.使用输入流循环读取文件中所有字符
(1)一个字节一个字节读取
public void testFileInputStream() {
FileInputStream input =null;
try {
input = new FileInputStream("Test/demo02.txt");
int a =-1;
while( (a = input.read())>-1 ) {//read()方法读取到文件末尾会返回-1
System.out.print((char)a);//将int类型强制转换为char类型
}//中文不止占有一个字节
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(input!=null)
input.close();//关闭输入流,释放资源
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
(2)按字节数组读取read(byte[] b);
法一
public void testFileInputStream() {
FileInputStream input =null;
try {
input = new FileInputStream("Test/demo02.txt");
byte[] data = new byte[4];
int length = -1;
while( (length = input.read(data))>-1 ) {
for(int i=0;i<length;i++) {
System.out.print((char)data[i]);
}
}
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(input!=null)
input.close();//关闭输入流,释放资源
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
法二
public void testFileInputStream() {
FileInputStream input =null;
try {
input = new FileInputStream("Test/demo02.txt");
byte[] data = new byte[4];
int length = -1;
while( (length = input.read(data))>-1 ) {
String str = new String(data,0,length);
System.out.print(str);
}
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(input!=null)
input.close();//关闭输入流,释放资源
} catch (IOException e) {
e.printStackTrace();
}
}
}
}