文件字节输入输出
1.创建File对象,封装需要写入的文件
2.创建FileInputStream流对象,建立起程序和数据源的连接
3.按照每次读取一个字节,读取文件的内容,为字符的编码
4.按照每次读取n个字节,读取文件内容,保存到字节数组中,返回的int是实际读取字节数。
5.关闭流对象,释放资源
File file = new File("D:/test2/txt");
FileInputStream fis = new FileInputStrem(file);
int len = -1;
byte[] buf = new byte[2];
while((len=fis.read(buf))!=-1){
String string = new String(buf,0,len);
}
fis.close();
输入输出步骤基本相同
文件的拷贝
1.创建FileInputStream、ileOutputStream对象
2.每次读取文件的内容并写入
**创建FileInputStream对象**
FileInputStream fis=new FileInputStream("D:/test/1.png");
**创建FileOutputStream对象**
FileOutputStream fos=new FileOutputStream("D:/test2/1.png");
**读取文件的内容,每次读取4个字节**
int len=-1; //读取的实际长度
byte[] buf=new byte[4];
每次读取4个字节
while((len=fis.read(buf))!=-1) {
System.out.println(Arrays.toString(buf));
每次写入4个字节
fos.write(buf,0,len);
}
fis.close();
fos.close();
}