IO的处理

1. 【io】流及File对象的处理(一)

2. 【io】流及File对象的处理(二)

 

本文主要介绍流的相关内容

1. 流的概念

是内存与存储设备之间传输数据的通道。

 

2. 流的分类

# 1. 按照方向分:
(1)输入流:将<存储设备>中的内容读入到<内存>中
(2)输出流:将<内存>中的内容写入到<存储设备># 2. 按处理单位分:
(1)字节流:以字节为单位,可以读写所有数据
(2)字符流:以字符为单位,只能读写文本数据
# 3. 按功能分:
(1)节点流:具有实际传输数据的读写功能。
(2)过滤流:在节点流的基础之上增强功能。

 

3. 字节流

3.1 字节流

# 字节流的父类(抽象类)
(1)InputStream:字节输入流(read)
(2)OutputStream:字节输出流(write)
# 文件字节流
    #(1)FileInputStream:
    #(2)FileOutputStream:

例子:

# 单个字节读取
public static void main(String[] args) throws Exception {//这里为了代码可读性,异常暂时抛出
    //1. 创建FileInputStream,并指定文件路径
    FileInputStream fis = new FileInputStream("d:\\aa.txt");
    //2. 读取文件 data对象用来保存我们读取的字节
    int data = 0;
    //如果都读取完了,会返回-1 ,不过这个read方法读取比较慢,是一个字节一个字节的读
    while ((data=fis.read())!=-1){
    System.out.println((char)data);//假设txt文件中存的是abcdefg ,那么每次会输出一个
    }
    //3. 关闭
    fis.close();
}

# 多个字节读取
public static void main(String[] args)  throws Exception{
    //1. 创建FileInputStream,并指定文件路径
    FileInputStream fis = new FileInputStream("d:\\aa.txt");
    //2. 创建一个数组用来存放读取到的字节,这里暂定长度为3
    byte[] buf = new byte[3];
    //3. 读取文件 count就是我们实际读取的字节数
    int count = 0;
    //如果都读取完了,会返回-1 ,这个read方法,是按照上面数组的长度,即三个三个的读
    while ((count=fis.read(buf))!=-1){
    System.out.println(new String(buf,0,count));//假设txt文件中存的是abcdefg ,那么每次会输出三个
    }
    //4. 关闭
    fis.close();
}

# 输出流写入
public static void main(String[] args) throws Exception{
    //1. 创建文件字节输出流对象 ,没有此文件会创建,有此文件调用下面的write方法的时候会覆盖txt里的内容。
    FileOutputStream fos = new FileOutputStream("d:\\bb.txt");
    //可以通过加参数 true 来实现非覆盖而是追加的效果
    //FileOutputStream fos = new FileOutputStream("d:\\bb.txt",true);
    //2. 写入文件.
    String str = "helloword";
    //str.getBytes()意思为获取这个字符串所对应的字符数组
    fos.write(str.getBytes());
    //3. 关闭
    fos.close();
}

# 使用文件字节流(输入流和输出流)实现文件的复制
# 注意:文件字节流不带缓冲效率会比较低
public static void main(String[] args) throws Exception{
    //1. 创建流
    //1.1 文件字节输入流 ,如果没有会报错java.io.FileNotFoundException: d:\001.jpg (系统找不到指定的文件。)
    FileInputStream fis = new FileInputStream("d:\\001.jpg");
    //1.2 文件字节输出流
    FileOutputStream fos = new FileOutputStream("d:\\002.jpg");
    //2. 一边读,一边写
    byte[] buf = new byte[1024];
    int count =0;
    while((count=fis.read(buf))!=-1){
    fos.write(buf,0,count);
    }
    //3. 关闭
    fis.close();
    fos.close();
}
View Code

相关文章:

  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
  • 2022-02-26
  • 2021-04-13
  • 2021-12-27
  • 2021-06-14
  • 2021-10-10
猜你喜欢
  • 2022-12-23
  • 2021-11-17
  • 2021-08-29
  • 2021-12-10
  • 2022-02-05
  • 2021-06-13
  • 2022-02-02
相关资源
相似解决方案