IO and files

IO and files

File

An object of the File class, representing a file or a file directory (commonly known as a folder)

package com.atguigu.java;

import java.io.File;
import java.io.IOException;

public class FileTest {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File file1 = new File("hello.txt");//相对路径,相对当前module
        System.out.println(file1.getAbsoluteFile());
        System.out.println(file1.getPath());
        System.out.println(file1.getName());
        System.out.println(file1.getParent());
        System.out.println(file1.length());
        System.out.println(file1.lastModified());


        String[] list = file1.list();
        for(String s: list){
    
    
            System.out.println(list);
        }
        File[] files = file1.listFiles();
        for(File f:files){
    
    
            System.out.println(files);
        }
        System.out.println(file1.isDirectory());
        System.out.println(file1.isFile());
        System.out.println(file1.exists());
        System.out.println(file1.canRead());
        System.out.println(file1.isHidden());

        if(!file1.exists())
            file1.createNewFile();
        else {
    
    
            file1.delete();
        }
        file1.mkdir();
        file1.mkdirs();
    }
}

The File class involves methods such as file or file directory creation, deletion, renaming, modification time, file size, etc., and does not involve writing or reading file contents. If you need to read or write the contents of the file, you must use the IO stream to complete.

Classification of streams

  • Byte stream
  • Input stream, output stream
  • Node flow

Stream system

Insert picture description here

Buffer stream

When closing the stream, close the outside first, and then close the inside. (When the outer stream is closed, the inner stream will be automatically closed) The
buffer stream reads and writes faster. Reading and writing will open up a space in memory.

Conversion flow

Provides conversion between byte stream and character stream

  • InputStreamReader
  • OutputStreamWriter
    example: convert utf-8 files to gbk files

package com.atguigu.java;

import java.io.*;

public class HelloWorld {
    
    
    public static void main(String[] args) throws IOException {
    
    
        File file1 = new File("dbcp.txt");
        File file2 = new File("dbcp_bgk.txt");

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

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

        char[] cbuf = new char[20];

        int len;
        while ((len = isr.read(cbuf)) != -1){
    
    
            osw.write(cbuf,0,len);
        }
        isr.close();
        osw.close();


    }
}

Standard input and output stream

  1. Standard input and output stream
    System, in standard input stream, the default input from the keyboard, the type is InputStream
    System, out standard output stream, the default output from the console, the type is PrintStream, which is a subclass of OutputStream
  2. The SetIn()/Setout() method of the System class re-specifies the input and output streams
  3. Exercise: Input a character string from the keyboard, and require that the entire line of character string read be converted to uppercase output, and then continue the input operation
package com.atguigu.java;

import java.io.*;

public class HelloWorld {
    
    
    public static void main(String[] args) throws IOException {
    
    

        InputStreamReader isr = new InputStreamReader(System.in);

        BufferedReader br = new BufferedReader(isr);
        String data;
        while(true){
    
    
            data = br.readLine();
            if("e".equals(data) || "exit".equals(data))
                break;
            String upperCase = data.toUpperCase();
            System.out.println(upperCase);
        }
        br.close();


    }
}

Print stream

PrintStream and PrinterWriter provide a series of overloaded methods print() and println()
to print the System.out.println() method to the specified file

package com.atguigu.java;

import java.io.*;

public class HelloWorld {
    
    
    public static void main(String[] args) throws IOException {
    
    
        PrintStream ps = null;
        try {
    
    
            FileOutputStream fos = new FileOutputStream(new File("D:\\IO\\text.txt"));
            ps = new PrintStream(fos,true);
            if(ps != null){
    
    
                System.setOut(ps);
            }

            for(int i = 0;i <= 255;i ++){
    
    
                System.out.println((char)i);
                if(i % 50 == 0)
                    System.out.println();
            }

        }catch (Exception e){
    
    
            ps.close();
        }

    }
}

data flow

DataInputStream和DataOutputStream

package com.atguigu.java;

import java.io.*;

public class HelloWorld {
    
    
    public static void main(String[] args) throws IOException {
    
    
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
        dos.writeUTF("刘建辰");
        dos.flush();
        dos.writeInt(23);
        dos.writeBoolean(true);
        dos.flush();
        dos.close(); 
    }
}

Object stream

For ObjectInputStream and ObjectInputStream
objects to be serializable, the object class must implement the Serializable interface.
Function: You can write the object in java to the data source and restore the object from the data source.
The object must specify the static type constant serialVersionUID
static And transient modified attributes cannot be serialized

package com.atguigu.java;

import java.io.*;

public class HelloWorld {
    
    
    public static void main(String[] args){
    
    
        ObjectOutputStream oos = null;
        try {
    
    
            oos = new ObjectOutputStream(new FileOutputStream("object.dat"));
            oos.writeObject(new String("我爱北京天安门"));
            oos.flush();
        }catch (IOException e){
    
    
            e.printStackTrace();
        }finally {
    
    
            if(oos != null)
            {
    
    
                try {
    
    
                    oos.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        }


        ObjectInputStream ois = null;
        try {
    
    
            ois = new ObjectOutputStream(new FileInputStream("object.dat"));
            Object object = ois.readObject();
            String str = (String)object;
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if(ois != null) {
    
    
                try {
    
    
                    ois.close();
                } catch (IOException e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    }
}

RandomAccessFile type

  1. RandomAccessFile directly inherits from the Object class and implements the DataInput and DataOutput interfaces
  2. RandomAccessFile can be used as both an input stream and an output stream
  3. "R" is opened in read-only mode, "rw" is opened for reading and writing, "rwd" is opened for reading and writing: update of file content is synchronized, "rws" is opened for reading and writing: file content and meta are synchronized Data update
  4. If RandomAcessFile is used as the output stream, if the written file does not exist, it will be automatically created during the execution process. If the written file exists, the original file content will be overwritten. (By default, overwrite from scratch).

Guess you like

Origin blog.csdn.net/m0_46656833/article/details/111824362