字节输入流与字节输出流
定义
字节与字符的不同:字节指计算机语言,是我们所读不懂的,就好比我们打开txt文件,当这个文件是乱码的时候,可简单理解为这就是字节文件,当我们看得懂的,可简单理解为字符文件。
相关的命令
-
创建一个txt文件,以字节输出的方式,输入内容:10行hello
public class FileOutputStreamDemo02 { public static void main(String[] args) throws IOException { FileOutputStream fos3 = new FileOutputStream("src\\fos3.txt"); for (int i = 0; i < 10; i++) { fos3.write("hello" .getBytes()); fos3.write("\n" .getBytes());
-
将这个字节文件,输出到操作台上显示
int by; while((by = fis.read()) != -1){ System.out.println((char) by); by = fis.read(); }
-
将D盘下的"C:\Users\street\Desktop\窗里窗外.txt"文件,复制到C盘下的“src\fos3.txt”文件下
-
先创建出456.txt文件,再读取123.txt文件,将读取的内容,输入到456.txt文件中
-
public class FileOutputStreamDemo02 { public static void main(String[] args) throws IOException { //将异常抛出 //一个是读取的文件 窗里窗外.txt ,一个是要输出的文件fos3 FileInputStream fis = new FileInputStream("C:\\Users\\street\\Desktop\\窗里窗外.txt"); FileOutputStream fos3 = new FileOutputStream("src\\fos3.txt"); //抛出异常 //读取内内容的同时,输出内容 int by; while ((by = fis.read()) != -1){ fos3.write(by); } //释放资源 fis.close(); fos3.close(); } }
-
在1这个例子中,是以一次输入一个字节数据,那我们想以一次输入一个字节数组的方式,又会有什么不同。
public class FileOutputStreamDemo03 { public static void main(String[] args) throws IOException { FileInputStream fis = new FileInputStream("src\\fos.txt"); byte[] bytes = new byte[1024]; //数组长度为1024或1024的整数倍。 int len while ((len =fis.read(bytes)) != -1){ System.out.println(new String(bytes,0,len)); } } }
- 利用循环读取数组,当读取到de数组的长度为-1时,作为跳出循环的依据。
- 此处的len表示:读取到的数组长度,当没有数组可读取的时候,len为-1.
- 数组长度为1024或1024的整数倍,则可输出全部内容。
- 可这么理解:要读取1024位的数组,但是到了len=-1时,就停止读取。
-
利用字节流,复制图片。
- 根据字节流创建字节对象
- 根据目的地创建字节对象
- 读写数据,复制图片,(一次读取一个字节数组,一次写入一个字节数组)
- 释放内存
public class FileOutputStreamDemo03 { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("src\\foe4.png"); FileInputStream fis = new FileInputStream("C:\\Users\\street\\Desktop\\截屏保存文件\\Snipaste_2022-02-04_14-05-07.png"); byte[] bytes = new byte[1024]; int len; while ((len = fis.read(bytes)) != -1){ fos.write(bytes,0,len); } fos.close(); fis.close(); } }
-