【Java基础】· IO流习题详解

写在前面


        Hello大家好, 我是【麟-小白】,一位软件工程专业的学生,喜好计算机知识。希望大家能够一起学习进步呀!本人是一名在读大学生,专业水平有限,如发现错误不足之处,请多多指正!谢谢大家!!!

        如果小哥哥小姐姐们对我的文章感兴趣,请不要吝啬你们的小手,多多点赞加关注呀!❤❤❤ 爱你们!!!


目录

写在前面

什么是java序列化,如何实现java序列化?

使用处理流的优势有哪些?如何识别所使用的流是处理流还是节点流?

Java中有几种类型的流?JDK为每种类型的流提供了一些抽象类以供继承,请指出它们分别是哪些类?

什么是标准的I/O流?

数组有没有length()方法?String有没有length()方法?File有没有length()方法?ArrayList有没有length()方法?

选择

1.计算机处理的数据最终分解为▁AD▁的组合。

2.计算机处理的最小数据单元称为▁B▁。

3.字母、数字和特殊符号称为▁C▁。

4.▁ABC▁文件流类的 close 方法可用于关闭文件。

5.RandomAccessFile 类的▁A▁方法可用于从指定流上读取整数。

6.RandomAccessFile 类的▁B▁方法可用于从指定流上读取字符串。

7.RandomAccessFile 类的▁C▁方法可用于设置文件定位指针在文件中的位置。

8.在FilterOutputStream类的构造方法中,下面哪个类是合法的:_C_

编程题

1. 在指定的路径下新建一个 .txt 文件 "test.txt",利用程序在文件中写入如下内容:

2. 利用程序读取 test.txt 文件的内容, 并在控制台打印

3. 利用程序复制 test.txt 为 test1.txt

4. 列出当前目录下全部java文件的名称

5. 列出d:\ch9目录下Java源文件的名字及其大小,并删除其中的一个Java源文件?

6. 操作D盘下的my.txt文件

7. File类的作用是什么?它是一种流吗?

8. 使用File类删除某个文件夹(例如D盘下的temp文件夹)下的所有文件和文件夹:

9. 利用IO操作文件

10. 利用IO流操作文件

11. 利用IO流操作文件

12. 列出D盘下的所有文件,子目录中的文件,子目录的子目录都要列出,依次类推,总之D盘下所有的文件都要输出(50分)

13. 先将“欢迎您”写入到文件”hello.txt”中,再读取该文件中的内容。

14. 如果准备读取一个文件的内容,应当使用FileInputStream流还是FileOutputStream流?

15. 编写一个应用程序,将用户从键盘输入的10个整数存入文件,再顺序读出。

16. BufferedReader流能直接指向一个文件对象吗?

17. 编写程序向文本文件中写入自己的信息,格式为:姓名:XXX 性别:X 年龄:XX 班级:XXX,将该信息读出后显示的屏幕上后把文件删除。

18. 用缓冲字节流实现文件复制的功能

19. 通过Io流实现MP3文件创建和复印功能

20. 用(字节流)读取一张图片,读进来之后再输出到另一个文件中。

21. (字符流)读取一个文本文件,每行都追加一个“好”,在文件结尾再追加“完毕”。

22. 使用Java的输入、输出流将一个文本文件的内容按行读出,每读出一行就顺序添加行号,并写入到另一个文件中。

23. 使用RandomAccessFile流将一个文本文件倒置读出。

24. 使用ObjectInputStream类和ObjectOutputStream类有哪些注意事项?

结语


【IO流精讲

一文带你深入理解【Java基础】· IO流(上)

一文带你深入理解【Java基础】· IO流(中)

一文带你深入理解【Java基础】· IO流(下)


什么是java序列化,如何实现java序列化?

答:序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化。

可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。

序列化是为了解决在对对象流进行读写操作时所引发的问题。

序列化的实现:将需要被序列化的类实现Serializable接口,该接口没有需要实现的方法,

implements Serializable只是为了标注该对象是可被序列化的,然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,接着,使用ObjectOutputStream对象的writeObject(Object obj)方法就可以将参数为obj的对象写出(即保存其状态),要恢复的话则用输入流。


使用处理流的优势有哪些?如何识别所使用的流是处理流还是节点流?

【优势】对开发人员来说,使用处理流进行输入/输出操作更简单;使用处理流的执行效率更高。

【判别】处理流的构造器的参数不是一个物理节点,而是已经存在的流。而节点流都是直接以物理IO及节点作为构造器参数的。


Java中有几种类型的流?JDK为每种类型的流提供了一些抽象类以供继承,请指出它们分别是哪些类?

【答案】Java中按所操作的数据单元的不同,分为字节流和字符流。

字节流继承于InputStream和OutputStream类;

字符流继承于Reader和Writer。

按流的流向的不同,分为输入流和输出流。

按流的角色来分,可分为节点流和处理流。缓冲流、转换流、对象流和打印流等都属于处理流,使得输入/输出更简单,执行效率更高。


什么是标准的I/O流?

在java语言中,用stdin表示键盘,用stdout表示监视器。他们均被封装在System类的类变量in 和out中,对应于系统调用System.in和System.out。这样的两个流加上System.err统称为标准流,它们是在System类中声明的3个类变量:

public static InputStream in

public static PrintStream out

public static PrintStream err


数组有没有length()方法?String有没有length()方法?File有没有length()方法?ArrayList有没有length()方法?

数组没有length()方法,但是有length属性。

String和File有length()方法。

ArrayList没有length()方法,有size()方法获取有效元素个数。


选择

1.计算机处理的数据最终分解为▁AD▁的组合。

A 0

B 数据包

C 字母

D 1


2.计算机处理的最小数据单元称为▁B▁。

A 位

B 字节

C 兆

D 文件


3.字母、数字和特殊符号称为▁C▁。

A 位

B 字节

C 字符

D 文件


4.▁ABC▁文件流类的 close 方法可用于关闭文件。

A FileOutputStream

B FileInputStream

C RandomAccessFile

D FileWrite


5.RandomAccessFile 类的▁A▁方法可用于从指定流上读取整数。

A readInt

B readLine

C seek

D close


6.RandomAccessFile 类的▁B▁方法可用于从指定流上读取字符串。

A readInt

B readLine

C seek

D close


7.RandomAccessFile 类的▁C▁方法可用于设置文件定位指针在文件中的位置。

A readInt

B readLiIne

C seek

D close


8.在FilterOutputStream类的构造方法中,下面哪个类是合法的:_C_

A File

B InputStream

C OutputStream

D FileOutputStream


【答案】

1.难度:容易    答案:AD 知识点:计算机最终能处理的数据只能为 0 和 1。

2.难度:容易    答案:B 知识点:计算机处理的最小数据单元是字节。

3.难度:容易    答案:C 知识点:字符的概念。

4.难度:适中    答案: ABC 知识点:FileOutStream、FileInputStream、RandomAccessFile

文件流类的 close 方法可用于关闭文件。

5.难度:适中    答案:A 知识点:readInt方法的使用。

6.难度:适中    答案:B 知识点:readLIne方法的使用。

7.难度:适中    答案:C 知识点:seek 方法的使用。

8.难度:适中    答案:C 知识点:在FilterOutputStream类中只有一种结构:

public FilterOutputStream(OutputStream)。


编程题

分别使用字节流和字符流完成以下程序:

1. 在指定的路径下新建一个 .txt 文件 "test.txt",利用程序在文件中写入如下内容:

"Java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于 1995年5月推出的Java程序设计语言和Java平台(即JavaSE, JavaEE, JavaME)的总称。Java 技术具有 卓越的通用性、高效性、平台移植性和安全性,广泛应用于个人PC、数据中心、游戏控制台、科 学超级计算机、移动电话和互联网,同时拥有全球最大的开发者专业社群。在全球云计算和移动互 联网的产业环境下,Java更具备了显著优势和广阔前景。"

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * ClassName: IoTest
 * Package: com.athome
 * Description:
 * @Author: 麟-小白
 * Create: 2022/12/17 - 20:54
 * @Version: v1.0
 */
public class IoTest {
    public static void main(String[] args) {
        DataOutputStream dos = null;
        try {
            dos = new DataOutputStream(new FileOutputStream("D:\\ShangGuiGu\\code\\test.txt"));
            dos.writeUTF("Java是一种可以撰写跨平台应用软件的面向对象的程序设计语言," +
                    "是由Sun Microsystems公司于 1995年5月推出的Java程序设计语言和Java平台" +
                    "(即JavaSE, JavaEE, JavaME)的总称。Java 技术具有 卓越的通用性、高效性、平台移植性和安全性," +
                    "广泛应用于个人PC、数据中心、游戏控制台、科 学超级计算机、移动电话和互联网,同时拥有全球最大的开发者专业社群。" +
                    "在全球云计算和移动互 联网的产业环境下,Java更具备了显著优势和广阔前景。");
            dos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2. 利用程序读取 test.txt 文件的内容, 并在控制台打印

public void test2() {
    InputStreamReader isr = null;
    try {
        isr = new InputStreamReader(new FileInputStream("D:\\ShangGuiGu\\code\\test.txt"), StandardCharsets.UTF_8);
        char[] cbuf = new char[1024];
        int len;
        while ((len = isr.read(cbuf)) != -1) {
            System.out.println(new String(cbuf, 0, len));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3. 利用程序复制 test.txt 为 test1.txt

public void test3() {
    BufferedReader br = null;
    BufferedWriter bw = null;
    try {
        br = new BufferedReader(new FileReader(new File("D:\\ShangGuiGu\\code\\test.txt")));
        bw = new BufferedWriter(new FileWriter(new File("D:\\ShangGuiGu\\code\\test1.txt")));
        char[] cbuf = new char[1024];
        int len;
        while ((len = br.read(cbuf)) != -1) {
            bw.write(cbuf, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bw != null) {
            try {
            bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4. 列出当前目录下全部java文件的名称

public void test4() {
    File srcFile = new File("D:\\ShangGuiGu\\code\\day01");
    String[] fileNames = srcFile.list();
    if (fileNames != null) {
        for (String fileName : fileNames) {
            if (fileName.endsWith(".java")) {
                System.out.println(fileName);
            }
        }
    }
}

5. 列出d:\ch9目录下Java源文件的名字及其大小,并删除其中的一个Java源文件?

public void test5() {
    File file = new File("d:\\ch9");
    String[] fileNames = file.list();
    int len;

    if (fileNames != null) {
        for (String fileName : fileNames) {
            if (fileName.endsWith(".java")) {
                len = fileNames.length;
                System.out.println("文件名:" + fileName + "文件大小:" + len);
            }
        }
    }
    delete(file);
}

private void delete(File file) {
    File[] files = file.listFiles();
    for (File file1 : files) {
        String name = file1.getName();
        if (name.endsWith(".java")) {
            System.out.println("删除成功:" + name);
            file.delete();
            break;
        }
    }
}

6. 操作D盘下的my.txt文件

  1. 判断my.txt文件是否存在
  2. 若存在则删除;若不存在则创建
public void test6() {
    File file = new File("d:\\mt.txt");
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("创建成功!");
    } else {
        file.delete();
        System.out.println("删除成功!");
    }
}

7. File类的作用是什么?它是一种流吗?

答:File类是I/O包中唯一能够代表磁盘文件本身的对象,使用File类,我们可以方便地建立与某磁盘文件的连接。一个对应着某磁盘文件或目录的File对象一经创建,我们就可以通过调用它的方法来获得该文件或目录的属性,File类中还定义了一些对文件或目录进行管理、操作的方法,利用这些方法可以完成对文件和目录的建立、删除、查询、重命名等操作。

File是一个类,不是一种流,声明在java.io下。


8. 使用File类删除某个文件夹(例如D盘下的temp文件夹)下的所有文件和文件夹:

  1. 判断temp文件夹下的文件类型,如果是文件则直接删除
  2. 如果是文件夹则获取该文件夹下的子文件和文件夹
  3. 使用递归的方式删除所有temp文件夹下的文件和文件夹
public class Test {
    public static void main(String[] args) {
        File fe = new File("I:\\cd9\\");
        judge(fe);
        File dl = new File("I:\\cd9\\temp\\Test");
        delete(dl);
    }

    public static void judge(File fe) {
        if (fe.isDirectory()) {
            File[] fi = fe.listFiles();
            if (fi != null) {
                for (File file : fi) {
                    File[] all = file.listFiles();
                    if (all != null) {
                        for (File f : all) {
                            judge(f);
                            System.out.println(f);
                        }
                    }
                }
            }
        } else {
            fe.delete();
        }
    }

    public static void delete(File dl) {
        if (dl.isDirectory()) {
            File[] all = dl.listFiles();
            for (File f : all) {
                delete(f);
            }
        }
        dl.delete();
    }
}

9. 利用IO操作文件

1)利用代码在D盘下创建news文件夹。

2)利用代码在news文件夹下创建2个.docx文件,2个.java文件,2个.txt的文件(在控制台打印news文件夹下的.java文件

public class Test {
    public static void main(String[] args) {
        File file = new File("I:\\cd9\\news");
        file.mkdir();
        try {
            File file1 = new File("I:\\cd9\\news\\test01.docx");
            File file2 = new File("I:\\cd9\\news\\test02.docx");
            File file3 = new File("I:\\cd9\\news\\test01.java");
            File file4 = new File("I:\\cd9\\news\\test02.java");
            File file5 = new File("I:\\cd9\\news\\test01.txt");
            File file6 = new File("I:\\cd9\\news\\test02.txt");
            if (!file1.exists()) {
                file1.createNewFile();
                System.out.println("创建文件:" + file1);
            }
            if (!file2.exists()) {
                file2.createNewFile();
                System.out.println("创建文件:" + file2);
            }
            if (!file3.exists()) {
                file3.createNewFile();
                System.out.println("创建文件:" + file3);
            }
            if (!file4.exists()) {
                file4.createNewFile();
                System.out.println("创建文件:" + file4);
            }
            if (!file5.exists()) {
                file5.createNewFile();
                System.out.println("创建文件:" + file5);
            }
            if (!file6.exists()) {
                file6.createNewFile();
                System.out.println("创建文件:" + file6);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        String[] fileNames = file.list();
        for (String f : fileNames) {
            if (f.endsWith(".java")) {
                System.out.println(f);
            }
        }
    }
}


10. 利用IO流操作文件

1)利用Java代码创建D:\temp\temp1\temp2共3个文件夹

2)在temp文件夹下创建一个1.txt文件内容为hello,创建一个Hello.java文件

3)内容为public static void main(String[] args){},在temp1文件夹下创建同样的两个文件

4)输出temp文件夹下包括其子文件夹下,所有的.java文件

public class Test {
    public static void main(String[] args) {
        File file1 = new File("I:\\cd9\\temp\\temp1\\temp2");
        if (!file1.exists()) {
            file1.mkdirs();
            System.out.println("创建文件1");
        }

        File file2 = new File("I:\\cd9\\temp\\1.txt");
        if (!file2.exists()) {
            try {
                file2.createNewFile();
                System.out.println("创建文件2");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileWriter fw = null;
        try {
            fw = new FileWriter(file2, false);
            fw.write("hello");
            System.out.println("读出txt数据");
        } catch (IOException e) {
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                }
            }
        }
        File file3 = new File("I:\\cd9\\temp\\Hello.java");
        if (!file3.exists()) {
            try {
                file3.createNewFile();
                System.out.println("创建文件3");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileWriter fj = null;
        try {
            fj = new FileWriter(file3, false);
            fj.write("public static void main(String[] args){}");
            System.out.println("读出java内容");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fj != null) {

                try {
                    fj.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        File file4 = new File("I:\\cd9\\temp\\temp1\\1.txt");
        if (!file4.exists()) {
            try {
                file4.createNewFile();
                System.out.println("创建文件4");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        File file5 = new File("I:\\cd9\\temp\\temp1\\Hello.java");
        if (!file5.exists()) {
            try {
                file5.createNewFile();
                System.out.println("创建文件5");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        File file6 = new File("I:\\cd9\\temp");
        seek(file6);
    }

    public static void seek(File file6) {
        File[] fi = file6.listFiles();
        if (fi != null) {

            for (File file : fi) {
                if (file.getName().endsWith(".java")) {
                    System.out.println(file);
                }
                seek(file);
            }
        }
    }
}

11. 利用IO流操作文件

  1. 利用java代码在D盘下创建一个mytemp文件夹
  2. 显示D盘下所有的.Java文件,包括D盘的子文件夹下的.java文件
  3. 把上述显示的文件都复制到mytemp文件夹中
public class Test {
    public static void main(String[] args) {
        File file = new File("I:\\cd9\\mytemp");
        if (!file.exists()) {
            file.mkdirs();
        }
        File file1 = new File("I:\\cd9");
        seek(file1);
    }
    public static void seek(File file) {
        File[] files = file.listFiles();
        if (files != null) {
            for (File fe : files) {
                if (fe .isFile() && fe.getName().endsWith(".java")) {
                    try {
                        FileInputStream fr = new FileInputStream(fe);
                        FileOutputStream fw = new FileOutputStream("I:\\cd9\\mytemp\\" +fe.getName());
                        System.out.println("复制文件");
                        byte[] cbuf = new byte[1024];
                        int len;
                        while ((len = fr.read(cbuf)) != -1) {
                            fw.write(cbuf,0,len);
                        }
                        System.out.println(fe);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (fe.isDirectory()) {
                      seek(fe);
                }
            }
        }
    }
}

12. 列出D盘下的所有文件,子目录中的文件,子目录的子目录都要列出,依次类推,总之D盘下所有的文件都要输出(50分)

  1. 在列出的时候判断是否子文件夹(10分)
  2. 若不是子文件夹直接输出文件名(20分)
  3. 若是子文件夹使用递归的形式继续输出子目录中的文件(20分)
public class Test {
    public static void main(String[] args) {
        File file = new File("I:\\cd9");
        judge(file);
    }
    public static void judge(File file) {
        File[] fe = file.listFiles();
        if (file.isDirectory()) {
            if (fe != null) {
                for (File file1 : fe) {
                    System.out.println(file1);
                    File[] all = file1.listFiles();
                    if (all != null) {
                        for (File f : all) {
                            judge(f);
                            System.out.println(f);
                        }
                    }
                }
            }
        } else {
            if (fe != null) {
                for (File file2 : fe) {
                    System.out.println(file2);
                }
            }
        }
    }
}

13. 先将“欢迎您”写入到文件”hello.txt”中,再读取该文件中的内容。

public class Test {
    public static void main(String[] args) {
        File file= new File("I:\\cd9\\Test\\hello.txt");
        FileWriter fw = null;
        try {
            fw = new FileWriter(file,false);
            System.out.println("写入到文件");
            fw.write("欢迎您");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        FileReader fr = null;
        try {
            fr = new FileReader(file);
            int data = fr.read();
            System.out.print("文件内容为:");
            while (data != -1) {
                System.out.print((char)data);
                data = fr.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

14. 如果准备读取一个文件的内容,应当使用FileInputStream流还是FileOutputStream流?

答:FileInputStream


15. 编写一个应用程序,将用户从键盘输入的10个整数存入文件,再顺序读出。

public class Test {
    public static void main(String[] args) {
        System.out.println("请输入的10个整数:");
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        File file = new File("I:\\cd9\\TTT\\hello.txt");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(str.getBytes());
            System.out.println("已存入文件");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        FileReader fr = null;
        try {
            fr = new FileReader(file);
            int data = fr.read();
            System.out.println("内容为:");
            while (data != -1) {
                System.out.print((char) data);
                data = fr.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        sc.close();
    }
}

16. BufferedReader流能直接指向一个文件对象吗?

答:不能,要通过一个,底层的FileImputStream 类的对象,才能指向一个文件对象。


17. 编写程序向文本文件中写入自己的信息,格式为:姓名:XXX 性别:X 年龄:XX 班级:XXX,将该信息读出后显示的屏幕上后把文件删除。

public class Test {
    public static void main(String[] args) {
        System.out.println("填写自己的信息:");
        System.out.println("格式为:姓名:XXX 性别:X 年龄:XX 班级:XXX");
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        FileOutputStream file = null;
        try {
            file = new FileOutputStream("I:\\cd9\\TTT\\hello.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {

        }
        DataOutputStream fos = null;
        try {
            fos = new DataOutputStream(file);
            fos.write(str.getBytes());
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        sc.close();
        File file1 = new File("I:\\cd9\\TTT\\hello.txt");
        seek(file1);
        System.out.println("\n");
        delete(file1);
        }

    public static void seek(File file1) {
        FileReader fr = null;
        try {
            fr = new FileReader(file1);
            int data = fr.read();
            System.out.print("信息读出:");
            while (data != -1) {
                System.out.print((char)data);
                data = fr.read();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void delete(File file1) {
        System.out.println("已删除");
        file1.delete();
    }
}

18. 用缓冲字节流实现文件复制的功能

  1. 首先判断d盘是否存在a.txt文件。
  2. 若不存在则创建a.txt文件,然后把a.txt文件复制成acopy.txt
public class Test {
    public static void main(String[] args) {
        File srcFile = new File("I:\\cd9\\TTT\\a.txt");
        File destFile = new File("I:\\cd9\\TTT\\acopy.txt");
        if (!srcFile.exists()) {
            try {
                srcFile.createNewFile();
                System.out.println("创建成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        BufferedReader fr = null;
        BufferedWriter fw = null;
        try {
            fr = new BufferedReader(new FileReader(srcFile));
            fw = new BufferedWriter(new FileWriter(destFile));
            char[] cbuf = new char[1024];
            int len;
            System.out.println("复制成功");
            while ((len = fr.read(cbuf)) != -1) {
                fw.write(cbuf,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

19. 通过Io流实现MP3文件创建和复印功能

  1. 判断d:/歌曲.mp3文件是否存在
  2. 若不存在则创建d:/歌曲.mp3文件,创建完成后复制到 e:/歌曲.mp3
public class Test {
    public static void main(String[] args) {
        File srcFile = new File("I:\\cd9\\Test\\歌曲.mp3");
        File destFile = new File("I:\\cd9\\TTT\\歌曲.mp3");
        if (!srcFile.exists()) {
            try {
                srcFile.createNewFile();
                System.out.println("创建成功1");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(srcFile));
            bos = new BufferedOutputStream(new FileOutputStream(destFile));

            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            System.out.println("复制成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

20. 用(字节流)读取一张图片,读进来之后再输出到另一个文件中。

public class Test {
    public static void main(String[] args) {
        File srcFile = new File("I:\\cd9\\Test\\图片1.jpg");
        File destFile = new File("I:\\cd9\\TTT\\图片2.jpg");
        if (!srcFile.exists()) {
            try {
                srcFile.createNewFile();
                System.out.println("创建成功2");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(srcFile));
            bos = new BufferedOutputStream(new FileOutputStream(destFile));

            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            System.out.println("复制成功1");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (bos != null) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

21. (字符流)读取一个文本文件,每行都追加一个“好”,在文件结尾再追加“完毕”。

public class Test {
    public static void main(String[] args) {
        File file = new File("H:\\ioText\\homework.txt");
        BufferedReader br = null;
        BufferedWriter bw = null;
        ArrayList<String> arrayList = new ArrayList<>();
        try {
            br = new BufferedReader(new FileReader(file));
            String content = "";
            while ((content = br.readLine()) != null) {
                System.out.println(content);
                content += "好";
                arrayList.add(content);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            bw = new BufferedWriter(new FileWriter(file));
            for (int i = 0; i < arrayList.size(); i++) {
                if (i == arrayList.size() - 1) {
                    bw.write(arrayList.get(i));
                    bw.flush();
                } else {
                    bw.write(arrayList.get(i));
                    bw.newLine();
                    bw.flush();
                }
            }
            bw.write("完毕");
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

22. 使用Java的输入、输出流将一个文本文件的内容按行读出,每读出一行就顺序添加行号,并写入到另一个文件中。

public void test7() {
    BufferedReader br = null;
    BufferedWriter bw = null;
    ArrayList<String> list = null;
    try {
        br = new BufferedReader(new FileReader("C:\\test1.txt"));
        bw = new BufferedWriter(new FileWriter("C:\\test2.txt"));

        int count = 0;
        String str = "";
        list = new ArrayList<>();
        while ((str = br.readLine()) != null) {
            list.add(++count + str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    try {
        for (int i = 0; i < list.size(); i++) {
            bw.write(list.get(i));
            bw.newLine();
            bw.flush();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

23. 使用RandomAccessFile流将一个文本文件倒置读出。

public class Test {
    public static void main(String[] args) {
        try {
            RandomAccessFile raf = new RandomAccessFile("异常日志.txt", "r");
            String str = null;
            StringBuilder sb = new StringBuilder();
            while ((str = raf.readLine()) != null) {
                sb.append(str);
            s    b.append("\n");
            }
        } catch(IOException e) {
            e.printStackTrace();
        } finally {
            if(ref != null) {
                try {
                    raf.close();
                } catch(IOEception e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(sb.reverse());
    }
}

24. 使用ObjectInputStream类和ObjectOutputStream类有哪些注意事项?

答:值得注意:当用对象流写入或读出对象时,要保证对象是序列化的。这是为了保证能把对象写到文件,并能再次把对象正确读回到程序中。

Java 提供给我们的绝大多数对象都是所谓序列化的,比如组件等。一个类如果实现了 Serializable 接口,那么这个类创建的对象就是所谓序列化的对象。 Serializable 接口中的方法对程序是不可见的,因此实现该接口的类不需要实现额外的方法,当把一个序列化的对象写入到对象输出流时,JVM 就会实现 Serializable 接口中的方法, 按着一定格式的文本将对象写入到目的地。


结语


本人会持续更新文章的哦!希望大家一键三连,你们的鼓励就是作者不断更新的动力

猜你喜欢

转载自blog.csdn.net/qq_34025246/article/details/128356864