![]()
package IO.inputstream;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputStream {
public static void main(String[] args) {
}
/**
* 演示FileInputStream的使用(字节输入流 文件-->程序)
* @author 长空扯淡
*/
@Test
public void readFile01(){
String filePath = "e:\\hello.txt";
int readDate = 0;
java.io.FileInputStream fileInputStream = null;
try {
//创建FileInputStream对象,用来读取文件
fileInputStream = new java.io.FileInputStream(filePath);
//从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
//如果返回-1,表示读取完毕
while((readDate = fileInputStream.read())!=-1){
System.out.print((char)readDate);//转成char显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 使用read(byte[] b)//读取文件,提高效率
* @author 长空扯淡
*/
@Test
public void readFile02(){
String filePath = "e:\\hello.txt";
int readLen = 0;
//字节数组
byte[] buf = new byte[10];//一次读取8个字节
java.io.FileInputStream fileInputStream = null;
try {
//创建FileInputStream对象,用来读取文件
fileInputStream = new java.io.FileInputStream(filePath);
//从该输入流读取最多b.length字节的数据到字节数组。此方法将阻塞,直到某些输入可用
//如果返回-1,表示读取完毕
//如果读取正常,返回实际读取的字节数
while((readLen = fileInputStream.read(buf))!=-1){
System.out.print(new String(buf,0,readLen));//转成char显示
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭文件流,释放资源
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}