Java(8)I/O

1、 File class

1. File class overview

2. File class instantiation

3. Common methods of file class

Public Boolean renameto (file dest): rename the file to the specified file path. (in fact, copy the contents of file1 to File2 and delete file1)

For file1 Renameto (File2) requires that file1 exists and File2 does not exist

If you create a file or the file directory does not have a write letter path, it is under the project path by default.

2、 Principle of IO flow

1. Principle of IO flow

2. Understanding of input and output

3、 Classification of IO streams

1. Classification

2. Illustration

3. Four abstract base classes

4. IO stream system

4、 FileReader and filewriter

1. Comparison between unit test method in idea and relative path under main()

2. Reading data using FileReader

public void test1() throws IOException {
        //1.实例化File类,指明要操作的对象.这一步的目的是建立硬盘中的文件和Java中类的对应关系.
        File file = new File("hello1.txt");

        //2.提供具体的流.参数的作用就是帮助我们并连接上文件这个"大水库"
        FileReader fileReader = new FileReader(file);

        //3.用流读取到内存
        //read():返回读入的字符,是int需要转换为char.到了文件结尾返回-1
        int read = fileReader.read();
        while (read != -1) {
            System.out.print((char) read);
            read = fileReader.read();
        }

        //4.关闭流
        fileReader.close();
    }
    //整个过程结合图示去理解很合理
	/*
    优化:
        1.第三部可以在语法上的优化,但是效率其实是一样的
        2.为了保证关闭操作一定执行,使用try-catch-finally
        3.读入的文件一定要存在,否则会出现:FileNotFoundException
    */
public void test2() {

        FileReader fileReader = null;
        try {
            File file = new File("hello1.txt");

            fileReader = new FileReader(file);

            //改进1
            int read;
            while ((read = fileReader.read()) != -1){
                System.out.print((char) read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileReader != null)
                    fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//使用数组
char[] charBuffer = new char[5];
int len;//记录每次读入到charBuffer数组中的字符个数
while ((len = fileReader.read(charBuffer)) != -1){
    for (int i = 0; i < len; i++) {//这里要用len(读取的字符数)二不是数组的长度
        System.out.print(charBuffer[i]);
    }
}

//当然for循环也可以换位String的构造器来把字符串数组转换为String
String string = new String(charBuffer,len);
System.out.print(string);

3. Write out data using filewriter

File file = new File("hello2.txt");
FileWriter fw = new FileWriter(file);
fw.write("i have a dream!");
fw.close();
//最后用try-catch处理一下异常,上面的步骤更清晰一些

4. Copy text files using FileReader and filewriter

public void test5() throws IOException {
        File srcFile = new File("hello2.txt");
        File destFile = new File("hello3.txt");

        FileReader fr = new FileReader(srcFile);
        FileWriter fw = new FileWriter(destFile);

        char[] charBuffer = new char[5];
        int len;
        while ((len = fr.read(charBuffer)) != -1) {
            fw.write(charBuffer,len);//和用String来取是类似的★★★★★
        }

        fw.close();
        fr.close();
}
//最后用try-catch处理一下异常,上面的步骤更清晰一些

5. Tests that use FileReader and filewriter to copy pictures cannot be processed

5、 FileInputStream and fileoutputstream

1. What happens to text files with FileInputStream and fileoutputstream?

2. Determines whether to use character stream or byte stream

3. Copy pictures with FileInputStream and fileoutputstream

6、 Buffer stream

1. What are the buffered streams

BufferedInputStream、bufferedoutputstream、BufferedReader、BufferedWriter

2. Function

3. Cause

4. Copy pictures using buffered streams

public void test() throws IOException {
        //1.创建File
        File srcFile = new File("img1.png");
        File destFile = new File("img2.png");

        //2.创建流
        //2.1创建文件流
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);

        //2.2创建字节流
        BufferedInputStream bis = new BufferedInputStream(fis);
        bufferedoutputstream bos = new bufferedoutputstream(fos);

        //3.复制
        byte[] bytes = new byte[10];
        int len;
        while ((len = bis.read(bytes)) != -1){
            bos.write(bytes,len);
        }

        //4.关闭流
        bis.close();
        bos.close();
}

5. Copy text files using buffered streams

public void test1() throws IOException {
        //1.创建文件和流
        BufferedReader br = new BufferedReader(new FileReader(new File("hello1.txt")));
        BufferedWriter bw = new BufferedWriter(new FileWriter(new File("hello4.txt")));

//        //2.复制
//        char[] chars = new char[10];
//        int len;
//        while ((len = br.read(chars)) != -1) {
//            bw.write(chars,len);
//        }


        // 复制:用String来实现★★★★★★★★★★★
        String data;//但是是不带换行的,可以用一以下两种方法实现
        while ((data = br.readLine()) != null) {
//          //方法一★★★★★★★★
//            bw.write(data + "\n");
            //方法二★★★★★★★★
            bw.write(data);
            bw.newLine();
        }

        //3.关闭
        br.close();
        bw.close();
    }

6. Exercise: count the number of occurrences of each character in the text

7、 Conversion flow

1. What is a transformation flow

2. Encoding and decoding

3. Character set

4. Function diagram of conversion flow

5. Exercises

@Test
    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,len);
        }

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

8、 Standard I / O stream (understand)

1. Introduction

2. Practice

public class Exercise {
    public static void main(String[] args) {//idea不支持在单元测试中输入内容,所以改用main()来测试
        BufferedReader br = null;
        try {
            InputStreamReader isr = new InputStreamReader(system.in);
            br = new BufferedReader(isr);

            while (true) {
                System.out.println("请输入字符串: ");
                String data = br.readLine();
                if ("e".equalsIgnoreCase(data)||"exit".equalsIgnoreCase(data)){
                    System.out.println("程序结束");
                    break;
                }
                String upperCase = data.toUpperCase();
                System.out.println(upperCase);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

9、 Print stream (understand)

1. Introduction to print stream

2. Code demonstration

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

10、 Data flow (understand)

1. Introduction

2. Practice

练习:将内存中的字符串、基本数据类型的变量写出到文件中。

    注意:处理异常的话,仍然应该使用try-catch-finally.
     */
    @Test
    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();


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

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

     */
    @Test
    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();

    }

11、 Object flow

1. Introduction

2. Serialization of objects ★★★★

3. The code implements the serialization and deserialization of the object of the string class

public class ObjectInputOutputStream {
    /*
    代码实现String类的对象的序列化和反序列化
     */

    @Test//序列化
    public void testObjectOutputStream(){
        ObjectOutputStream oos = null;
        try {
            //1.造流和文件
            oos = new ObjectOutputStream(new FileOutputStream(new File("objectString.dat")));
            //2.写出
            oos.writeObject(new String("我爱你中国"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //3.关闭流
            try {
                if (oos != null) {
                    oos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testObjectInputStream(){
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream(new File("objectString.dat")));

            Object readObject = ois.readObject();
            System.out.println(readObject);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

4. Serialization of custom classes

5. Interview questions

12、 RandomAccessFile

1. Introduction

2. Using RandomAccessFile class to copy text files

@Test
public void test1() throws IOException {
    //用参数mode标识,让类代表输入
    RandomAccessFile r = new RandomAccessFile(new File("hello1.txt"),"r");
    //用参数mode标识,让类代表输出
    RandomAccessFile rw = new RandomAccessFile(new File("hello5.txt"),"rw");

    byte[] bytes = new byte[1024];
    int len;
    while ((len=r.read(bytes)) != -1){
        rw.write(bytes,len);
    }

    r.close();
    rw.close();
}

3. Characteristics when using RandomAccessFile as output stream

4. How to use RandomAccessFile to insert text files

/*
    使用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,len)) ;
        }
        //调回指针,写入“xyz”
        raf1.seek(3);
        raf1.write("xyz".getBytes());

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

        raf1.close();
    }

13、 Use of third-party jar packages

1. Why

2. Import the third-party jar package from idea

3. Using third-party jar package to copy files

public class JarTest {
    public static void main(String[] args) throws IOException {
        File srcFile = new File("s6_IO/hello1.txt");
        File destFile = new File("s6_IO/hello6.txt");

        FileUtils.copyFile(srcFile,destFile);

    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>