字节流:传输的是字节,可以传输任何类型的数据
相关:
- 字节输出流:OutputStream
- 字节输入流:InputStream
- 字节缓冲输出流:BufferedOutputStream
- 字节缓冲输入流:BufferedInputStream
相关用法:
public class Demo02 {
public static void main(String[] args) throws IOException {
// 实现写
//fileWrite();
// 实现读1
//fileReader1();
// 实现读2
//fileReader2();
// 实现读3
fileReader3();
}
// 实现写
public static void fileWrite() throws IOException {
//1.创建输出流对象并关联文件
FileOutputStream fileOutputStream = new FileOutputStream("temp1.txt");
//2.写----因为使用的是字节流,所以不能直接传出字符,所以要进行编码
fileOutputStream.write("bingbing".getBytes());//对应的默认字符集是GBK
//刷新+关闭流
fileOutputStream.close();
}
// 实现读1:一个字节一个字节的读
public static void fileReader1() throws IOException {
//1.创建输入流对象
FileInputStream fileInputStream = new FileInputStream("temp1.txt");
//2.读
int num;
while((num=fileInputStream.read())!=-1) {
System.out.println((char)num);
}
fileInputStream.close();
}
// 实现读2:一次读取多个字节
public static void fileReader2() throws IOException {
FileInputStream fileInputStream = new FileInputStream("temp1.txt");
//2.读
byte[] arr = new byte[3];
int num;
while((num=fileInputStream.read(arr))!=-1) {
System.out.println(new String(arr,0,num));
}
fileInputStream.close();
}
// 实现读3:一次读取全部字节
public static void fileReader3() throws IOException {
FileInputStream fileInputStream = new FileInputStream("temp1.txt");
//2.获取所有的字节数
//注意:如果文本的字节数太大不建议使用
int nums = fileInputStream.available();
//3.读
byte[] arr = new byte[nums];
fileInputStream.read(arr);
System.out.println(new String(arr));
fileInputStream.close();
}
}
使用字节流读写图片:
public class Demo03 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("xiaoyan.jpg");
FileOutputStream fileOutputStream = new FileOutputStream("xiaoyan100.jpg");
//进行读写
int num;
byte[] arr = new byte[fileInputStream.available()];
fileInputStream.read(arr);
fileOutputStream.write(arr);
fileInputStream.close();
fileOutputStream.close();
}
}
字节缓冲流实现图片的复制:
public class Demo04 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("7d3bba0121bb46006e870053f0617f52.jpg");
FileOutputStream fileOutputStream = new FileOutputStream("copy7d3bba0121bb46006e870053f0617f52.jpg");
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
//进行读写
byte[] arr = new byte[fileInputStream.available()];
bufferedInputStream.read(arr);
bufferedOutputStream.write(arr);
bufferedInputStream.close();
bufferedOutputStream.close();
}
}