第十章、Java基础语法----IO流

第十章、Java基础语法----IO流

本人也是刚入门Java语言,可能会有一些地方出现错误,描述的不对。如果发现不对的地方请及时指出,好对其进行修改。这样不仅可以让我学到东西,也可以让其他刚入门的朋友学习更正确的内容。

所有内容仅供参考。不具有完全的准确性!

注:关于Java的所有内容都会参考到尚硅谷在网上公开的学习视频及其提供的PPT

推荐:
https://blog.csdn.net/sinat_37064286/article/details/86537354
https://www.cnblogs.com/shuaiguoguo/p/8883862.html

一、IO流的概述
(一)流是什么
流就像是一个通道,对应的通道可以传输指定的对象。河流中就可以输送水,河流中的流就相当于沟渠,这个沟渠负责将里边的水输送到其他地方,这也称为输出,被输送到的地方肯定需要接收这些水,这个接收的过程就叫输入。(比如黄河的水从黄河源流出,这个过程就是输出,最终流到渤海,这也叫输入)。

(二)IO流是什么
IO流也称为数据流,是计算机等电子设备中的一种流。这个流可以负责数据的输入输出。IO全程为:InputOutput,Input:输入,Output:输入

二、File类的使用
File:文件

(一)File类的理解

  1. File类的一个对象,代表一个文件或一个文件目录(俗称:文件夹)
  2. File类声明在java.io包下
  3. File类中涉及到关于文件或文件目录的创建、删除、重命名、修改时间、文件大小等方法,
    并未涉及到写入或读取文件内容的操作。如果需要读取或写入文件内容,必须使用IO流来完成
  4. 后续File类的对象常会作为参数传递到流的构造器中,指明读取或写入的"终点".

(二)如何使用

  1. 如何创建File类的实例
    File(String filePath) // 形参表示对应的文件路径,如果路径不对会报文件未找到异常
    File(String parentPath,String childPath) //parentPath表示childPath的上级路径
    File(File parentFile,String childPath)

  2. 相对路径:相较于某个路径下,指明的路径。
    绝对路径:包含盘符在内的文件或文件目录的路径

  3. 路径分隔符
    windows : \\ 或 ‘/’
    unix:/

例:
注意:eclipse和IDEA的相对路径不一样。IDEA中的相对路径在测试方法和main方法中也不一样

public void test1(){
        //构造器1 File(String path)
        File file1 = new File("Hello.txt");//相对于当前module
        File file2 = new File("F:\\IDEAWorkSpace\\IO"); //绝对路径

        System.out.println(file1);//Hello.txt
        System.out.println(file2);//File file5 = new File(file2,"test1");

//        File file3 = new File("TTTT");// 不是路径
//        System.out.println(file3);//TTTT

        //构造器2  File(String parent,String Child)
//        File file4 = new File("TER","d");//错误的路径
//        System.out.println(file4);//TER\d

        File file5 = new File("F:\\IDEAWorkSpace\\IO","test1");
        System.out.println(file5);//F:\IDEAWorkSpace\IO\test1

        //构造器3 File(File file,String Child)
        File file6 = new File(file5,"test1");
        System.out.println(file6);//F:\IDEAWorkSpace\IO\test1
    }

File类的常用方法:
public String getAbsolutePath():获取绝对路径
public String getPath() :获取路径
public String getName() :获取名称
public String getParent():获取上层文件目录路径。若无,返回null
public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
public long lastModified() :获取最后一次的修改时间,毫秒值

  public void test2(){
        File file1 = new File("Hello.txt");
        File file2 = new File("F:\\IDEAWorkSpace\\IO");

        //public String getAbsolutePath():获取绝对路径
        String path = file1.getAbsolutePath();
        String path1 = file2.getAbsolutePath();
        System.out.println(path);//F:\IDEAProject\FirstIDEAProject\IOStreamTest\Hello.txt
        System.out.println(path1); //F:\IDEAWorkSpace\IO

        File absoluteFile = file1.getAbsoluteFile();
        System.out.println(absoluteFile);//F:\IDEAProject\FirstIDEAProject\IOStreamTest\Hello.txt

        //public String getPath() :获取路径
        String path2 = file1.getPath();
        String path3 = file2.getPath();
        System.out.println(path2);//Hello.txt
        System.out.println(path3);//F:\IDEAWorkSpace\IO

        //public String getParent():获取上层文件目录路径。若无,返回null
        String parent = file1.getParent();
        System.out.println(parent);//null
        String parent1 = file2.getParent();
        System.out.println(parent1);//F:\IDEAWorkSpace

        //public String getName() :获取名称
        System.out.println(file1.getName());//Hello.txt
        System.out.println(file2.getName());//IO

        //public long length() :获取文件长度(即:字节数)。不能获取目录的长度。
        System.out.println(file1.length()); //0  .txt文件不存在  //12
        System.out.println(file2.length()); //0  IO不是文件,而是目录

        //public long lastModified() :获取最后一次的修改时间,毫秒值
        System.out.println(new Date(file1.lastModified())); //Sun Dec 06 10:53:14 CST 2020
        System.out.println(file2.lastModified());//1607221626225 目录也有修改时间

    }

如下的两个方法适用于文件目录:
public String[] list() :获取指定目录下的所有文件或者文件目录的名称数组
public File[] listFiles() :获取指定目录下的所有文件或者文件目录的File数组

 public void test3(){
        File file1 = new File("F:\\IDEAWorkSpace\\IO");

        //相对路径
        String[] list = file1.list();
        for(String s : list){
            System.out.println(s);//test1
        }

        System.out.println();

        //绝对路径
        File[] files = file1.listFiles();
        for(File f : files){
            System.out.println(f);//F:\IDEAWorkSpace\IO\test1
        }

    }

创建硬盘中对应的文件或文件目录

public boolean createNewFile() :创建文件。若文件存在,则不创建,返回false
public boolean mkdir() :创建文件目录。如果此文件目录存在,就不创建了。如果此文件目录的上层目录不存在,也不创建。
public boolean mkdirs() :创建文件目录。如果此文件目录存在,就不创建了。如果上层文件目录不存在,一并创建

删除磁盘中的文件或文件目录
    public boolean delete():删除文件或者文件夹

删除注意事项:Java中的删除不走回收站。
 public void test7(){
        //文件目录的创建
        File file1 = new File("d:\\io\\io1\\io3");

        boolean mkdir = file1.mkdir();
        if(mkdir){
            System.out.println("创建成功1");
        }

        File file2 = new File("d:\\io\\io1\\io4");

        boolean mkdir1 = file2.mkdirs();
        if(mkdir1){
            System.out.println("创建成功2");
        }
        //要想删除成功,io4文件目录下不能有子目录或文件
        File file3 = new File("D:\\io\\io1\\io4");
        file3 = new File("D:\\io\\io1");
        System.out.println(file3.delete());

    }

三、IO流原理及流的分类

(一)IO流原理

  • I/O是Input/Output的缩写, I/O技术是非常实用的技术,用于处理设备之间的数据传输。如读/写文件,网络通讯等。

  • Java程序中,对于数据的输入/输出操作以“流(stream)” 的方式进行。

  • java.io包下提供了各种“流”类和接口,用以获取不同种类的数据,并通过标准的方法输入或输出数据。

  • 输入input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。

  • 输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中。

(二)流的分类

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

(三)流的体系结构
在这里插入图片描述
说明:红框对应的是IO流中的4个抽象基类。
蓝框的流是常用类,需要掌握。

四、IO流的创建和使用

(一)文本文件的输入过程—字符流

  1. 创建File类的对象,指明读取的数据的来源。(要求此文件一定要存在)
  2. 创建相应的输入流,将File类的对象作为参数,传入流的构造器中
  3. 具体的读入过程:
    创建相应的byte[] 或 char[]
  4. 关闭流资源
    说明:程序中出现的异常需要使用try-catch-finally处理。如果不关闭流就会占用系统资源,消耗内存。(FileWriter流没有关闭的话,写的内容将不会出现在文件中)

例:

public void test1(){
        FileReader fr = null;
        try {
            //1.实例化File类的对象,指明要操作的文件
            File file = new File("hello.txt"); //相对路径:当前Module下
            //2.提供具体的流
            fr = new FileReader(file);
        //3.数据的读入
        //read():返回读入的一个字符。如果达到文件末尾,返回-1   每read()一次,索引下边就向后一位
        //方式一:
//        int data = fr.read();  //将字符转换成数组(有利于下边做循环时的判断条件)
//        while(data != -1){
//            System.out.print((char)data);//hello World   北极光 (因为data是int型,需要转会到char型)
//            data = fr.read(); // 类似于.next 输出下一个数组
//        }

        //方式二:语法上针对于方式一的修改
        int data;
        while((data = fr.read()) != -1){
            System.out.print((char)data);
        }

		//方式三:使用read(cbuf, 0, cbuf.length)方法
		char[] cbuf = new char[5];//用于存储读取到的数据
		int len;
        while((len = fr.read(cbuf)) != -1){
        //使用的String构造器注意区分read(char[] cbuf,int offset,int length); 形参列表相同
           String str = new String(cbuf,0,len);
           System.out.println(str);
        }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //4. 操作执行完,一定要关闭流
            try {
                //因为上边在实例化File对象和提供具流的时候都有出现异常的可能
                //所以此处要判断fr是否实例化了,若没有实例化就执行close(),会报空指针异常
                if(fr != null)
                    fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

(二)文本文件的输出过程—字符流

  1. 创建File类的对象,指明写出的数据的位置。(不要求此文件一定要存在)
  2. 创建相应的输出流,将File类的对象作为参数,传入流的构造器中
  3. 具体的写出过程:
    write(char[]/byte[] buffer,0,len)
  4. 关闭流资源
    说明:程序中出现的异常需要使用try-catch-finally处理。

说明:

  1. 输出操作,对应的File可以不存在的。并不会报异常
  2. File对应的硬盘中的文件如果不存在,在输出的过程中,会自动创建此文件。
    File对应的硬盘中的文件如果存在:
          如果流使用的构造器是:FileWriter(file,false) / FileWriter(file):对原有文件的覆盖
          如果流使用的构造器是:FileWriter(file,true):不会对原有文件覆盖,而是在原有文件基础上追加内容
public void test3(){
        FileWriter fw = null;

        try {
            //1.提供File类的对象,指明写出到的文件
            File file = new File("Hi.txt");
            //2.提供FileWriter的对象,用于数据的写出
            fw = new FileWriter(file);		
			
			//注意:
			//不能使用字符流来处理图片等字节数据,虽然最后图片的文件可以创建出来,但图片是无法查看的
            File readFile = new File("Lisa.jpg");
            File writeFile = new File("pretty.jpg");
			
			
            //3.写出的操作
            //write(int c) 写入的是ASCII码,到在实际写入以后会转成char型字符
//        fw.write(65);//A
            fw.write("ABCCCCDE");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4. 关闭写入流 (若不关闭,文档中将看不到写入的数据)
            try {
                if(fw != null)
                    fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

(三)非文本文件的输入输出过程—字节流
使用字节流可以处理文本文件,但可能出现乱码。

   /*
    实现对图片的复制操作
     */
    @Test
    public void test2() {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            // 1. 实例化File,指定操作路径
            File file = new File("Lisa.jpg");

            // 2. 实例化具体流
            fis = new FileInputStream(file);
            fos = new FileOutputStream("LisaSister.jpg");

            // 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 {
            // 4. 关闭流
            if(fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

结论:

  1. 对于文本文件(.txt,.java,.c,.cpp),使用字符流处理
  2. 对于非文本文件(.jpg,.mp3,.mp4,.avi,.doc,.ppt,…),使用字节流处理

五、缓冲流

作用:提供流的读取、写入的速度
提高读写速度的原因:内部提供了一个缓冲区。默认情况下是8kb
在这里插入图片描述缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为:

  1. BufferedInputStream 、 BufferedOutputStream
  2. BufferedReader 、 BufferedWriter

当使用BufferedInputStream读取字节文件时,BufferedInputStream会一次性从文件中读取8192个(8Kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。

流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,
BufferedOutputStream才会把缓冲区中的数据一次性写到文件里。使用方法flush()可以强制将缓冲区的内容全部写入输出流

注意:
关闭流的时候要先从最外层的流开始关闭。不过系统设置了只要关闭最外层流即可,关闭最外层流也会相应关闭内层节点流
如果是带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,关闭后不能再写出

例一:文本文件的缓冲流


 public void test2(){
        BufferedReader br = null;
        BufferedWriter bw = null;

        try {
            // 1. 创建文件路径和缓冲流
            br = new BufferedReader(new FileReader("hello.txt"));
            bw = new BufferedWriter(new FileWriter("hello2.txt"));

            // 2. 操作流
            char[] cbuf = new char[5];
            int len;
            //方式一
            //读取指定字节个数
//            while((len = br.read(cbuf)) != -1){
//                bw.write(cbuf,0,len);
//            }

            //方式二
            //读取整行(不包含换行符)
            // 注意: 需要使用String接收
            String str;
            while((str = br.readLine()) != null){
                bw.write(str);//输出结果不会换行(换行方式一:加换行符 或 使用bw的方法)
                bw.newLine(); //只是一个换行作用
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 3. 关闭流
            if(br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }


例二:非文本文件的缓冲流

    @Test
    public void BufferedStreamTest() throws FileNotFoundException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            //1.造文件
            File srcFile = new File("爱情与友情.jpg");
            File destFile = new File("爱情与友情3.jpg");
            //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[10];
            int len;
            while((len = bis.read(buffer)) != -1){
                bos.write(buffer,0,len);

//                bos.flush();//刷新缓冲区

            }
        } 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();
        }
    }

六、转换流

转换流提供了在字节流和字符流之间的转换
提供了两个转换流:
InputStreamReader:将InputStream转换为Reader
OutputStreamWriter:将Writer转换为OutputStream
字节流中的数据都是字符时,转成字符流操作更高效。
很多时候我们使用转换流来处理文件乱码问题。实现编码和解码的功能。

(一) InputStreamReader
将一个字节的输入流转换为字符的输入流
解码:字节、字节数组 —>字符数组、字符串

public void test1() throws IOException {

        FileInputStream fis = new FileInputStream("dbcp.txt");
//        InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集
        //参数2指明了字符集,具体使用哪个字符集,取决于文件dbcp.txt保存时使用的字符集
        InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//使用系统默认的字符集

        char[] cbuf = new char[20];
        int len;
        while((len = isr.read(cbuf)) != -1){
            String str = new String(cbuf,0,len);
            System.out.print(str);
        }

        isr.close();

    }

注意:
因为这个是举例,所以异常就通过throws抛出了,实际编写程序中一定要使用try-catch。
如果使用throws抛异常,最后因为文件路径等问题导致程序终止,此时就无法关系相关的数据流。就会造成资源的浪费。通过try-catch-finally,即使抛出了异常也可以关闭数据流

(二)OutputStreamWriter
将一个字符的输出流转换为字节的输出流
编码:字符数组、字符串 —> 字节、字节数组

说明:编码决定了解码的方式

综合使用OutputStreamWriter 和 InputStreamReader

 注意:处理异常的话,仍然应该使用try-catch-finally.
public void test2() throws Exception {
        //1.造文件、造流
        File file1 = new File("dbcp.txt");
        File file2 = new File("dbcp_gbk.txt");

        FileInputStream fis = new FileInputStream(file1);
        FileOutputStream fos = new FileOutputStream(file2);

        InputStreamReader isr = new InputStreamReader(fis,"utf-8");
        OutputStreamWriter osw = new OutputStreamWriter(fos,"gbk");

        //2.读写过程
        char[] cbuf = new char[20];
        int len;
        while((len = isr.read(cbuf)) != -1){
            osw.write(cbuf,0,len);
        }

        //3.关闭资源
        isr.close();
        osw.close();


    }

在这里插入图片描述

七、标准的输入输出流

System.in和System.out分别代表了系统标准的输入和输出设备
System.in:标准的输入流,默认从键盘输入
System.out:标准的输出流,默认从控制台输出

  • 默认输入设备是:键盘,输出设备是:显示器
    System.in的类型是InputStream
    System.out的类型是PrintStream,其是OutputStream的子类

  • FilterOutputStream 的子类
    重定向:通过System类的setIn,setOut方法对默认设备进行改变。
    public static void setIn(InputStream in)
    public static void setOut(PrintStream out)

八、打印流

实现将基本数据类型的数据格式转化为字符串输出
用到的类:
PrintStream 和 PrintWriter
说明:
提供了一系列重载的print()和println()方法,用于多种数据类型的输出
System.out返回的是PrintStream的实例

 public void test2() {
        PrintStream ps = null;
        try {
            FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
            // 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
            ps = new PrintStream(fos, true);
            if (ps != null) {// 把标准输出流(控制台输出)改成文件
                System.setOut(ps);
            }


            for (int i = 0; i <= 255; i++) { // 输出ASCII字符
                System.out.print((char) i);
                if (i % 50 == 0) { // 每50个数据一行
                    System.out.println(); // 换行
                }
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ps != null) {
                ps.close();
            }
        }

    }

九、数据流
数据流
DataInputStream 和 DataOutputStream

  • 作用:用于读取或写出基本数据类型的变量或字符串

注意:处理异常的话,仍然应该使用try-catch-finally.

public void test3() throws IOException {
        //1.
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
        //2.
        dos.writeUTF("刘建辰");
        dos.flush();//刷新操作,将内存中的数据写入文件
        dos.writeInt(23);
        dos.flush();
        dos.writeBoolean(true);
        dos.flush();
        //3.
        dos.close();


    }

练习:将文件中存储的基本数据类型变量和字符串读取到内存中,保存在变量中。

注意点:读取不同类型的数据的顺序要与当初写入文件时,保存的数据的顺序一致

 public void test4() throws IOException {
        //1.
        DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
        //2.
        String name = dis.readUTF();
        int age = dis.readInt();
        boolean isMale = dis.readBoolean();

        System.out.println("name = " + name);
        System.out.println("age = " + age);
        System.out.println("isMale = " + isMale);

        //3.
        dis.close();

    }

十、对象流

用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把Java中的对象写入到数据源中,也能把对象从数据源中还原回来。

ObjectInputStream和OjbectOutputSteam

ObjectOutputStream:内存中的对象—>存储中的文件、通过网络传输出去:序列化过程
ObjectInputStream:存储中的文件、通过网络接收过来 —>内存中的对象:反序列化过程

序列化:用ObjectOutputStream类保存基本类型数据或对象的机制
反序列化:用ObjectInputStream类读取基本类型数据或对象的机制

ObjectOutputStream和ObjectInputStream不能序列化static和transient修饰的成员变量

序列化机制:
对象序列化机制允许把内存中的Java对象转换成平台无关的二进制流,从而允许把这种二进制流持久地保存在磁盘上,或通过网络将这种二进制流传输到另一个网络节点。当其它程序获取了这种二进制流,就可以恢复成原来的Java对象

好处:
可将任何实现了Serializable接口的对象转化为字节数据,使其在保存和传输时可被还原

序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去

public void testObjectOutputStream(){
        ObjectOutputStream oos = null;

        try {
            //1.
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            //2.
            oos.writeObject(new String("我爱北京天安门"));
            oos.flush();//刷新操作

            oos.writeObject(new Person("王铭",23));
            oos.flush();

            oos.writeObject(new Person("张学良",23,1001,new Account(5000)));
            oos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(oos != null){
                //3.
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }

反序列化过程:将磁盘文件中的对象还原为内存中的一个java对象

public void testObjectInputStream(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("object.dat"));

            Object obj = ois.readObject();
            String str = (String) obj;

            Person p = (Person) ois.readObject();
            Person p1 = (Person) ois.readObject();

            System.out.println(str);
            System.out.println(p);
            System.out.println(p1);

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

            }
        }
    }

补充:
实现序列化的对象所属的类需要满足:

  1. 需要实现接口:Serializable
  2. 当前类提供一个全局常量:serialVersionUID
  3. 除了当前Person类需要实现Serializable接口之外,还必须保证其内部所属性也必须是可序列化的。(默认情况下,基本数据类型可序列化)

十一、随机存取文件流
RandomAccessFile
与其说是随机读取流,其实该流的功能和随机没有任何关系,而是通过该流可以实现对文件读和写两种功能,相比之前的流只能读或只能写要方便的多。所以也可称之为:任何读写流

RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
RandomAccessFile既可以作为一个输入流,又可以作为一个输出流

如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建。
如果写出到的文件存在,则会对原文件内容进行覆盖。(默认情况下,从头覆盖)
可以通过相关的操作,实现RandomAccessFile“插入”数据的效果。seek(int pos)
在这里插入图片描述

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();
                }

            }
        }
    }

使用RandomAccessFile实现数据的插入效果

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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值