IO流是一组有序的用于程序输入和输出操作的数据序列
一、字节输入流FileInputStream【读入Input】
程序以字节为单位从磁盘文件读取数据
/**
* 通过字节输入流FileInputStream,【读取】电脑中文件的内容
* 外面的【读】进来 in
* @throws IOException
*/
@Test
public void test1() throws IOException{ //读 FileInputStream
//创建FileInputStream对象,作用是:以字节为单位读取文件的内容
FileInputStream fis = new FileInputStream("Z:\\TestIO\\三国演义第1回.txt");
//读取未见内容,如果read():如果返回值不是-1,就说明还存在未读的字节
int i = 0;
String sum = "";
while((i = fis.read()) != -1){ //按照字节读取,所以不能有汉字,因为一个汉字占两个字节,必乱码
sum += (char)i;
System.out.println(i); //按照Ascll码值传递
}
System.out.println(sum);
fis.close(); //一定要及时关闭!!!
System.out.println("文件读取成功");
}
二、字节输出流FileOutputStream【写出Output】
程序以字节为单位,向磁盘文件写入数据
/**
* 通过字节输出流FileOutputStream,向电脑中文件【写入】内容、
* 自己的【写】出去 out
* @throws IOException
*/
@Test
public void test2() throws IOException{ //写 FileOutputStream
//创建FileOutputStream对象,作用是:以字节为单位向文件中写入内容
FileOutputStream fos = new FileOutputStream("Z:\\TestIO\\三国演义第2回.txt");
//向文件写入内容
fos.write("Hello World".getBytes());
fos.close(); //一定要及时关闭!!!
System.out.println("文件写入成功");
}
三、案例
/**
* 文件拷贝(复制粘贴)
* @throws IOException
*/
@Test
public void test3() throws IOException{
FileInputStream fis = new FileInputStream("C:\\Users\\张子伦\\Desktop\\流.jpg");
FileOutputStream fos = new FileOutputStream("Z:\\TestIO\\流.jpg");
int b;
while((b = fis.read()) != -1){
fos.write(b);
}
fos.close(); //后用先关
fis.close(); //先用后关
}