IO流——文件的读写操作,重要的流结构

目录

1. File类

1.1 说明

1.2 File的实例化

1.3 File类的常用方法

2. IO流

2.1 重要流结构(inputstream/outputstream 字节流,reader/writer 字符流)

2.2 FileReader/FileWriter的使用:

2.2.1 输入过程(读取)

2.2.2 输出过程

2.3 FileInputStream / FileOutputStream的使用:

2.4 使用BufferedInputStream和BufferedOutputStream:处理非文本文件

2.5 使用BufferedReader和BufferedWriter:处理文本文件

3. 随机存取文件流:RandomAccessFile


1. File类

1.1 说明

  1. File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
  2. File类声明在java.io包
  3. File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,不能读取或写入文件内容(使用IO流实现)

1.2 File的实例化

构造器:  File(String filePath)
                File(String parentPath,String childPath)

相对路径:相较于某个路径下,指明的路径。

相对路径在IDEA和Eclipse中使用的区别
IDEA:
如果使用单元测试方法,相对路径基于当前的Module的。
如果使用main()测试,相对路径基于当前Project的。

Eclipse:
单元测试方法还是main(),相对路径都是基于当前Project的

绝对路径:包含盘符在内的文件或文件目录的路径

路径分隔符
windows和DOS系统默认使用“\”来表示
UNIX和URL使用“/”来表示

1.3 File类的常用方法

2. IO流

2.1 重要流结构(inputstream/outputstream 字节流,reader/writer 字符流)

* 1.操作数据单位:字节流(8bit)、字符流(16bit)
* 2.数据的流向:输入流、输出流
* 3.流的角色:节点流、处理流

* 1. 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
* 2. 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,...),使用字节流处理
缓冲流   作用:提高流的读取、写入的速度
 原因:内部提供了一个缓冲区。默认情况下是8kb
        使用BufferedInputStream和BufferedOutputStream:处理非文本文件
        使用BufferedReader和BufferedWriter:处理文本文件
转换流  作用:提供字节流与字符流之间的转换   其属于字符流
        InputStreamReader:将一个字节的输入流转换为字符的输入流
                解码:字节、字节数组  --->字符数组、字符串
        InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//字符集需与文件保持一致
        OutputStreamWriter:将一个字符的输出流转换为字节的输出流
                编码:字符数组、字符串 ---> 字节、字节数组
        OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
对象流  作用:内存中的对象二进制流的相互转换
ObjectOutputStream:内存中的对象--->存储中的文件、通过网络传输出去:序列化过程
     
  oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
        oos.writeObject(new String("我爱北京天安门"));
        oos.flush();//刷新操作
ObjectInputStream:存储中的文件、通过网络接收过来 --->内存中的对象:反序列化过程
        ois = new ObjectInputStream(new FileInputStream("object.dat")); 
        Object obj = ois.readObject();
        String str = (String) obj;

2.2 FileReader/FileWriter的使用:

2.2.1 输入过程(读取)

① 创建File类的对象=File类的实例化,指明读取的数据的来源。
File file = new File("hello.txt");
读入的文件一定要存在,否则就会报FileNotFoundException。
② 创建相应的输入流=FileReader流的实例化,将File类的对象作为参数,传入流的构造器中
FileReader fr = new FileReader(file);
③ 具体的读入过程:
1.read():返回读入的一个字符。如果达到文件末尾,返回-1
int data;
while((data = fr.read()) != -1){
      System.out.print((char)data);
}
2.创建相应的byte[] 或 char[]。
    read(char[] cbuf):返回每次读入cbuf数组中的字符的个数。如果达到文件末尾,返回-1
char[] cbuf = new char[5];
    int len;
    while((len = fr.read(cbuf)) != -1){
       for(int i = 0;i < len;i++){
            System.out.print(cbuf[i]);
        }
    }
关闭流资源
  if(fr != null)
        fr.close();
异常的处理:为了保证流资源一定可以执行关闭操作。需要使用try-catch-finally处理//ALT+SHIFT+Z
try{ 操作1,2,3
}catch (IOException e) {
    e.printStackTrace();
} finally {操作4(注意close()异常,try-catch)}

2.2.2 输出过程

创建File类的对象,指明写出的数据的位置。(不要求此文件一定要存在)
File file = new File("hello1.txt");
   File对应的硬盘中的文件如果不存在,自动创建此文件。
② 创建相应的输出流,将File类的对象作为参数,传入流的构造器中
FileWriter fw = new FileWriter(file,false);
具体的File对应的硬盘中的文件如果存在:
    如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
    如果流使用的构造器是:FileWriter(file,true):在原有文件基础上追加内容
FileWriter(pathname,append)
③ 写出过程:
    write(char[]/byte[] buffer,0,len)
 fw.write("I have a dream!\n");
④ 关闭流资源
if(fw != null)  fw.close();
说明:程序中出现的异常需要使用try-catch-finally处理。

2.3 FileInputStream / FileOutputStream的使用:

/*
实现对图片的复制操作
 */
@Test
public void testFileInputOutputStream()  {
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
        //1.造文件
        File srcFile = new File("爱情与友情.jpg");
        File destFile = new File("爱情与友情2.jpg");

        //2.造流
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);

        //3.复制的过程
        byte[] buffer = new byte[5];
        int len;
        while((len = fis.read(buffer)) != -1){
            fos.write(buffer,0,len);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(fos != null){
            //4.关闭流
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if(fis != null){
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

}

2.4 使用BufferedInputStream和BufferedOutputStream:处理非文本文件

1.造文件
2.造流——造节点流,造缓冲流
3.复制的细节:读取、写入
            byte[] buffer = new byte[1024];
            int len;
            while((len = bis.read(buffer)) != -1){  //通过缓冲流对象操作
                bos.write(buffer,0,len);
            }
4.资源关闭   要求:先关闭外层的流(缓冲流),再关闭内层的流(节点流)(随外层自动关闭)

//实现文件复制的方法
    public void copyFileWithBuffered(String srcPath,String destPath){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            //1.造文件
            File srcFile = new File(srcPath);
            File destFile = new File(destPath);
            //2.造流
            //2.1 造节点流
            FileInputStream fis = new FileInputStream((srcFile));
            FileOutputStream fos = new FileOutputStream(destFile);
            //2.2 造缓冲流
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);

            //3.复制的细节:读取、写入
            byte[] buffer = new byte[1024];
            int len;
            while((len = bis.read(buffer)) != -1){
                bos.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源关闭
            //要求:先关闭外层的流,再关闭内层的流
            if(bos != null){
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            if(bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            //说明:关闭外层流的同时,内层流也会自动的进行关闭。关于内层流的关闭,我们可以省略.
//        fos.close();
//        fis.close();
        }
    }

2.5使用BufferedReader和BufferedWriter:处理文本文件

public void testBufferedReaderBufferedWriter(){
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            //创建文件和相应的流
            br = new BufferedReader(new FileReader(new File("dbcp.txt")));
            bw = new BufferedWriter(new FileWriter(new File("dbcp1.txt")));

            //读写操作
            //方式一:使用char[]数组
//            char[] cbuf = new char[1024];
//            int len;
//            while((len = br.read(cbuf)) != -1){
//                bw.write(cbuf,0,len);
//    //            bw.flush();
//            }

            //方式二:使用String
            String data;
            while((data = br.readLine()) != null){
                //方法一:
//                bw.write(data + "\n");//data中不包含换行符
                //方法二:
                bw.write(data);//data中不包含换行符
                bw.newLine();//提供换行的操作

            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(bw != null){

                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br != null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

3. 随机存取文件流:RandomAccessFile

  1. RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
  2. RandomAccessFile既可以作为一个输入流,又可以作为一个输出
            raf2 = new RandomAccessFile(new File("爱情与友情1.jpg"),"rw");
  3. 如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则自动创建
  4. 如果写出到的文件存在,则会对原文件内容进行覆盖。(默认情况下,从头覆盖)
  5.  可以通过相关的操作,实现RandomAccessFile“插入”数据的效果。
    seek(int pos) 将指针调到角标为pos的位置
      raf1.write("插入的数据".getBytes());
@Test
public void test1() {

    RandomAccessFile raf1 = null;
    RandomAccessFile raf2 = null;
    try {
        //1.
        raf1 = new RandomAccessFile(new File("爱情与友情.jpg"),"r");
        raf2 = new RandomAccessFile(new File("爱情与友情1.jpg"),"rw");
        //2.
        byte[] buffer = new byte[1024];
        int len;
        while((len = raf1.read(buffer)) != -1){
            raf2.write(buffer,0,len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //3.
        if(raf1 != null){
            try {
                raf1.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if(raf2 != null){
            try {
                raf2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

典型代码2:

/*
使用RandomAccessFile实现数据的插入效果
 */
@Test
public void test3() throws IOException {

    RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");

    raf1.seek(3);//将指针调到角标为3的位置
    //保存指针3后面的所数据到StringBuilder中
    StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
    byte[] buffer = new byte[20];
    int len;
    while((len = raf1.read(buffer)) != -1){
        builder.append(new String(buffer,0,len)) ;
    }
    //调回指针,写入“xyz”
    raf1.seek(3);
    raf1.write("xyz".getBytes());

    //将StringBuilder中的数据写入到文件中
    raf1.write(builder.toString().getBytes());

    raf1.close();

    //思考:将StringBuilder替换为ByteArrayOutputStream
}

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值