This is the 27th day of my participation in the August More Text Challenge

The file object

  • Common methods for file objects
import java.io.File;

public class Demo{
    public static void main(String[] args){
        File f1 = new File("/home/cunyu/soft/Java");
        
        // Absolute path
        System.out.println("F1 absolute path:" + f1.getAbsolutePath());
        
        // create a file object with f1 as the parent directory
        File f2 = new File(f1, "Demo.java");
        System.out.println("F2 Absolute path:" + f2.getAbsolutePath());
        
        File f3 = new File("/home/cunyu/soft/Java/Demo.java");
        
        // Check whether the file exists
        System.out.println(f3.exists());
        
        // Check whether the file is a folder
        System.out.println(f3.isDirectory());
        
        // Check whether it is a file
        System.out.println(f3.isFile());
        
        // File length
        System.out.println(f3.length());
        
        // Change the last time
        long time = f3.lastModified();
        Date date = new Date(time);
        System.out.println(d)
        
        // Set the file modification time from 1970.1.1 08:00:00
        f3.setLastModified(0);
        
        // Rename the file
        File f4 = new File("/home/cunyu/soft/Java/Test.java");
        f3.renameTo(f4);
        
        // Return all files in the current folder as an array of strings (excluding subfiles and subfolders)
        String[] filesListStr = f3.list();
        
        // Return all files in the current folder as an array of files (excluding subfiles and subfolders)
        File[] filesListFile = f3.listFiles();
        
        // Returns the file folder as a string
        String pathStr = f3.getParent();
        
        // Create a folder
        f3.mkdir(); // The parent folder does not exist
        f3.mkdirs(); // The parent folder does not exist
        
        // Create an empty file
        f3.createNewFile();
        
        // Lists the drive letters
        f3.listRoots();
        
        // Delete files
        f3.delete();
        
        // Delete files when the JVM terminates, often used to delete temporary filesf3.deleteOnExit(); }}Copy the code

Stream (Stream)

  • define: When data is interacted between different media,JavaThe data source can be files, databases, networks, etc. From different angles, it can be divided intoThe input stream,InputStream)The output stream (OutputStream);
  • The instance
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Demo{
    public static void main(String[] args){
        try{
            File file = new File("/home/cunyu/soft/Java/Demo.java");
            
            / / input stream
            FileInputStream inputStream = new FileInputStream(file);
            / / the output stream
            FileOutputStream outputStream = new FileOutputStream(file);
        } catch(IOException e){ e.printStackTrace(); }}}Copy the code

Byte stream VS character stream VS cache stream VS data stream VS object stream

Byte stream

  • Definition: Divided into InputStream and OutputStream, mainly used for reading and writing data in the form of bytes;
  • Visible ASCII codes corresponding to decimal and hexadecimal;
character Decimal digit A hexadecimal number
! 33 21
34 22
# 35 23
$ 36 24
% 37 25
& 38 26
39 27
( 40 28
) 41 29
* 42 2A
+ 43 2B
. 44 2C
45 2D
. 46 2E
/ 47 2F
0 48 30
1 49 31
2 50 32
3 51 33
4 52 34
5 53 35
6 54 36
7 55 37
8 56 38
9 57 39
: 58 3A
; 59 3B
< 60 3C
= 61 3D
> 62 3E
@ 64 40
A 65 41
B 66 42
C 67 43
D 68 44
E 69 45
F 70 46
G 71 47
H 72 48
I 73 49
J 74 4A
K 75 4B
L 76 4C
M 77 4D
N 78 4E
O 79 4F
P 80 50
Q 81 51
R 82 52
S 83 53
T 84 54
U 85 55
V 86 56
W 87 57
X 88 58
Y 89 59
Z 90 5A
[ 91 5B
\ 92 5C
] 93 5D
^ 94 5E
_ 95 5F
` 96 60
a 97 61
b 98 62
c 99 63
d 100 64
e 101 65
f 102 66
g 103 67
h 104 68
i 105 69
j 106 6A
k 107 6B
l 108 6C
m 109 6D
n 110 6E
o 111 6F
p 112 70
q 113 71
r 114 72
s 115 73
t 116 74
u 117 75
v 118 76
w 119 77
x 120 78
y 121 79
z 122 7A
{ 123 7B
| 124 7C
} 125 7D
~ 126 7E
  • Example: Read and write data in byte stream form
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo{
    public static void main(String[] args){
        // Read data
        try{
            File fileIn = new File("/home/cunyu/soft/Java/Demo.java");
            FileInputStream fis = new FileInputStreaam(fileIn);
            
            // Create a byte array of file length
            byte[] fileContext = new byte[(int)file.length()];
            
            // Read the contents of the file as a byte stream and close the stream after use
            fis.read(fileContext);
            fis.close();
        } catch(IOException e){
            e.printStackTrace();
        }
        
        // Write data
        try{
            File fileOut = new File("/home/cunyu/soft/Java/Demo.java");
            FileOutputStream fos = new FileOutputStream(fileOutput);
            
            // Write data to the corresponding byte array
            byte[] data = {65.66.67};
            
            // Write data as a byte stream, then close the stream
            fos.write(data);
            fos.close()
        } catch(IOException e){ e.printStackTrace(); }}}Copy the code

Characters of the flow

  • Definition: a character input stream (Reader) and a character output stream (Writer) are used to read and input data in the form of characters.
  • Example: Character streams read and input data
import java.io.IOException;
import java.io.FileReader;
import java.io.File;

public class Demo{
    public void main(String[] args){
        
        / / read
        File file = new File("/home/cunyu/soft/Java/Demo.java");
        
        try(FileReader fileReader = new FileReader(file)){
            char[] all = new char[(int) file.length()];
            fileReader.read(all);
        } catch (IOException e){
            e.printStackTrace();
        }
        
        / / write
        try(FileWriter fileWriter = new FileWriter(file)){
            String data = "System.out.println("hello world");";
            char[] strArray = data.toCharArray();
            fileWriter.write(strArray);
        } catch(IOException e){ e.printStackTrace(); }}}Copy the code

Cache flow

  • Definition: Byte stream and character stream access the hard disk in each read/write. If the read/write frequency is high, the performance is poor. Therefore, cache stream is used. The cache stream reads a large amount of data to the cache at a time. Each subsequent read is accessed in the cache until the data in the cache is read and then read from the hard disk.
  • Example: The cache stream reads and writes data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Demo{
    public static void main(String[] args){
        File file = new File("/home/cunyu/soft/Java/Demo.java");
        
        / / read
        try(
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
       		)
        {
            while(true) {// One line at a time
                String line = br.readLine();
                if(line ! =null){
                    System.out.println(line)
                }else{
                    break; }}}catch (IOException){
            e.printStackTrace();
        }
        
         / / write
        try(
            FileWriter fw = new FileWriter(file);
            BufferedWriter wr = new BufferedWriter(fw);
       		)
        {
            while(true) {// One line at a time
                String line = wr.writeLine();
                if(line ! =null){
                    System.out.println(line)
                }else{
                    break; }}}catch(IOException){ e.printStackTrace(); }}}Copy the code
  • flush: cache both read and write need to wait until the cache is full, but sometimes need to read and write immediately, can be usedflushRead and write immediately;
package stream;
   
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Demo {
    public static void main(String[] args) {
        File file = new File("/home/cunyu/soft/Java/Demo.java");
        
        // Create a file character stream
        // The cache stream must be based on an existing stream
        try(FileWriter fr = newFileWriter(f); PrintWriter pw =new PrintWriter(fr);) {
            pw.println("garen kill teemo");
            // Force data from the cache to be written to disk, whether the cache is full or not
            pw.flush();            
            pw.println("teemo revive after 1 minutes");
            pw.flush();
            pw.println("teemo try to garen, but killed again");
            pw.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch blocke.printStackTrace(); }}}Copy the code

The data flow

  • Definition: DataInputStream (DataInputStream) and DataOutputStream (DataOutputStream);
  • Example: Read and write strings directly;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo{
    public static void main(String[] args){
        File file = new File("/home/cunyu/soft/Java/Demo.java");
        write();
        read();
    }
    
    /** * Data stream writes *@param: file File to be written */
    public static viod write(File file){
        try(FileOutputStream fos = new FileOutputStream(file);
           DataOutputStream dos = newDataOutputStream(fos);) { dos.writeBoolean(true);
            dos.writeInt(250);
            dos.writeUTF("You're 250?");
        } catch(IOException e){ e.printStackTrace(); }}/** * Data stream read *@param: file File to be written */
    public static viod read(File file){      
        try(
        	FileInputStream fis = new FileInputStream(file);
            DataInputStream dis = newDataInputStream(fis); ) {boolean b = dis.readBoolean();
            int i = dis.readInt();
            String str = dis.readUTF();
        } catch(IOException e){ e.printStackTrace(); }}}Copy the code

Object flow

  • define: refers to the directTo stream an objectTo other media. An object transmitted as a stream is calledserialization, the class to which the object belongs must be implementedSerializableInterface;
  • Example: Serialize an object;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

class Hero implements Serializable{
    private static final long serialVersionUID = 1L;
    public String name;
    public float hp;
}

public class Demo{
    public static void main(String[] args){
        Hero hero = new Hero();
        hero.name = "Armor";
        hero.hp = 1000;

        // The text used to save the object
        File file = new File("/home/cunyu/soft/Java/k.honor");

        try(
            // Object input stream
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);

            // Object output stream
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = newObjectOutputStream(fos); ) { oos.writeObject(hero); Hero hero2 = (Hero) ois.readObject(); System.out.println(hero2.name +":" + hero2.hp);
        } catch (IOException e){
            e.printStackTrace();
        } catch(ClassNotFoundException e){ e.printStackTrace(); }}}Copy the code

Chinese problem

  • Common coding:
    1. ISO-8859-1 ASCII: numbers and Western European letters;
    2. GBK GB2312 BIG5: Chinese;
    3. UNICODE: unified coding;
  • Example: Read Chinese;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
 
public class Demo {
 
    public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException {
        File f = new File("/home/cunyu/tmp/test.txt");
        System.out.println("Default encoding:" + Charset.defaultCharset());
        //FileReader gets characters, so bytes must have been recognized as characters based on some encoding
        // The encoding used by FileReader is the return value of charset.defaultCharset (),
        try (FileReader fr = new FileReader(f)) {
            char[] cs = new char[(int) f.length()];
            fr.read(cs);
            System.out.println("Default encoding: %s",Charset.defaultCharset());
            System.out.println(new String(cs));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
       	// FileReader cannot set the encoding manually, so InputStreamReader is used instead
        try (InputStreamReader isr = new InputStreamReader(new FileInputStream(f),Charset.forName("UTF-8"))) {
            char[] cs = new char[(int) f.length()];
            isr.read(cs);
            System.out.printf(InputStreamReader (utF-8) : %n);
            System.out.println(new String(cs));
        } catch (IOException e) {
            // TODO Auto-generated catch blocke.printStackTrace(); }}}Copy the code

The way to close a stream

Shut down any flow after it is used. Otherwise, resources will be wasted and subsequent services may be affected. Here are three ways to shut down the flow.

  • Closed in try: An exception will be thrown if the file does not exist or there is a problem when reading the file, which will cause the code that cannot trigger the closing stream. Therefore, it has a huge potential resource consumption and is not recommended.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo{
    public static void main(String[] args){
        // Read data
        try{
            File fileIn = new File("/home/cunyu/soft/Java/Demo.java");
            FileInputStream fis = new FileInputStreaam(fileIn);
            
            // Create a byte array of file length
            byte[] fileContext = new byte[(int)file.length()];
            
            // Read the contents of the file as a byte stream and close the stream after use
            fis.read(fileContext);
            // Close the try
            fis.close();
        } catch(IOException e){ e.printStackTrace(); }}}Copy the code
  • 4. A standard way to close a stream in finally:
  1. Declare a reference to the stream intryOutside for conveniencefinallyAccess;
  2. Shut downfinallyBefore, determine whether the reference isnull;
  3. When closed, proceed againtry catchProcessing;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo{
    public static void main(String[] args){
        
        File fileIn = new File("/home/cunyu/soft/Java/Demo.java");
        FileInputStream fis = null;
        // Read data
        try{
            fis = new FileInputStream(fileIn);
            // Create a byte array of file length
            byte[] fileContext = new byte[(int)file.length()];
            
            // Read the contents of the file as a byte stream and close the stream after use
            fis.read(fileContext);
            // Close the try
            fis.close();
        } catch(IOException e){
            e.printStackTrace();
        } finally{
            if(fis ! =null) {try{
                    fis.close();
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}
Copy the code
  • try()The way of: defines the flow intry()When theTry, catch, finallyWhen it ends, the stream is automatically closed;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
  
public class TestStream {
  
    public static void main(String[] args) {
        File fileIn = new File("/home/cunyu/soft/Java/Demo.java");
  
        // Define the stream ina try(). When a try,catch, or finally ends, it is automatically closed
        try (FileInputStream fis = new FileInputStream(fileIn)) {
            byte[] all = new byte[(int) f.length()];
            fis.read(all);
        } catch(IOException e) { e.printStackTrace(); }}}Copy the code

Input and output

  • defineSystem.inUsed to enter data from the console,System.outUsed to output data on the console;

Flow diagram

Graph RL B [byte stream] -- > A flow [character] [current] C - > A flow] [D] [cache flow - > C [character] streaming data flow - > B/byte stream object flow - > B (bytes)

conclusion

That’s all I have to say about IO streaming. If you found this article helpful, just like it!