Java IO字节输入输出流

水深无声 2024-03-31 17:13 183阅读 0赞

Java的输入输出功能来自java.io 包中InputStream类、OutputStream类

OutPutStream(输出流) 使用:

  1. // 文件路径
  2. File f1 = new File("C:\\Users\\Yxb\\Desktop\\test.txt");
  3. // 因为OutputStream是抽象类 没法实例化 通过向上转型实例化子类来使用
  4. OutputStream out = new FileOutputStream(f1);

通过.write()方法向文件中写入内容

  1. out.write(97);

892fb4635464419286b3d1fca4b83f68.png

可以看到写入的内容是a 这是因为它是根据ASCII码表来写入内容的。我们如果向写入东西还要对照ASCII码表来输入所对应的十进制数字,这样效率太慢了,那么我们应该怎样写入自己想要写入的内容呢?

我们可以将想要写入的内容写在String类型中,然后通过String类的.getBytes()方法将这些内容变成byte数组,然后通过.write()方法向文件中写入内容,参数为byte数组

  1. String str = "97";
  2. out.write(str.getBytes());

c90ba39ff77f41e5b4edd86ca5dbfecd.png

这样就可以写入我们想要写入的内容了。

可是现在还有一个问题,如果我们每次运行代码它都会将原本的内容替换成我们想要输入的内容,没法接着后面继续写入。这是因为它的FileOutputStream参数后面会默认是false,我们只需要改成true即可

  1. OutputStream out = new FileOutputStream(f2,false);// (默认false)替换原本内容
  2. OutputStream out = new FileOutputStream(f2,true);// 在原本的内容后面继续写入

InputStream(输入流) 使用:

  1. File f1 = new File("C:\\Users\\Yxb\\Desktop\\test.txt");
  2. InputStream in = new FileInputStream(f1);

.read()进行读操作

  1. // 如果到达流末尾而没有可用的字节,则返回值 -1
  2. int read = in.read();
  3. // read为ASCII码表中所对应的十进制数字,使用强制类型转换变成char类型
  4. System.out.println((char)read);

这样我们每次就可以读取一个字节,这样效率太慢了。因为到达流末尾而没有可用的字节,则返回值 -1,那么我们可以使用循环来打印所有内容

  1. int n;
  2. while((n = in.read())>0){
  3. System.out.print((char)n);
  4. }

或者

  1. // 声明一个byte数组,长度随意
  2. byte[] b = new byte[10];
  3. // 声明一个int类型的值
  4. int i2;
  5. // while循环,将.read(b)的值赋值给i2,判断条件如果i2大于0则证明数组中有值,否则结束循环
  6. while ((i2 = in.read(b)) > 0) {
  7. // String的有参构造方法
  8. // String s = new String(byte[] b); 将byte数组传入String的构造方法中,打印s即可
  9. String s = new String(b,0,i2);
  10. System.out.print(s);
  11. }

小案例

将某个磁盘中的某个文件复制到桌面

  1. public class InputStreamTest02 {
  2. public static void main(String[] args) throws IOException {
  3. /*
  4. * 照片
  5. * */
  6. // 找到文件路径
  7. File f1 = new File("E:\\Test\\TestPic.jpeg");
  8. // 粘贴的路径
  9. File f2 = new File("C:\\Users\\Yxb\\Desktop\\paste\\pastePic.jpeg");
  10. // 实例化输入输出流
  11. InputStream in = new FileInputStream(f1);
  12. OutputStream out = new FileOutputStream(f2);
  13. // 定义一个byte数组长度为1024(长度多少都可以,长度如果太短运行效率就会慢,过长占用内存)
  14. byte[] b = new byte[1024];
  15. int n;
  16. while ((n = in.read(b)) > 0) {
  17. // 写入byte数组中的值,从第0个字节开始写入,长度为n
  18. out.write(b, 0, n);
  19. }
  20. /*
  21. * 视频
  22. * */
  23. File f3 = new File("E:\\Test\\TestVideo.mp4");
  24. File f4 = new File("C:\\Users\\Yxb\\Desktop\\paste\\pasteVideo.mp4");
  25. InputStream in2 = new FileInputStream(f3);
  26. OutputStream out2 = new FileOutputStream(f4);
  27. byte[] b2 = new byte[2048];
  28. int n2;
  29. while ((n2 = in2.read(b2)) > 0) {
  30. out2.write(b2, 0, n2);
  31. }
  32. }
  33. }

运行后效果图:

8f7ee771a400409fb24c92742d0bd78a.png

ce9bb11e722b4842a9054af37a271893.png

发表评论

表情:
评论列表 (有 0 条评论,183人围观)

还没有评论,来说两句吧...

相关阅读