Java learning -- file processing, generics and container classes

Keywords: Java Container

1, File processing

1. Create an object of File class

File Class creation function
 Method name:
1.public boolean creatNewFile()(When the file with this name does not exist, create a new empty file named by this abstract pathname)
2.public boolean mkdir()(Create a folder named after this abstract pathname)
3.public boolean mkdirs()(Create a folder named by this abstract path, and return if successful true,Otherwise return false

Case 1 (creating files and folders)

package text;
import java.io.File;
import java.io.IOException;
public class FileDemo1 {
    public static void main(String[] args)throws IOException {
        File f1=new File("D:\\cwy\\java.txt");
        System.out.println(f1.createNewFile());
        System.out.println("-----------");
        File f2=new File("D:\\cwy\\JavaSE");
        System.out.println(f2.mkdir());
        System.out.println("-----------");
        File f3=new File("D:\\cwy\\JavaWEB\\HTML");
        System.out.println(f3.mkdirs());
        System.out.println("-----------");
        File f4=new File("D:\\cwy\\javase.txt");
        System.out.println(f4.createNewFile());
        //System.out.println(f4.mkdir());
    }


}

Run result: if the file does not exist, create the file and return true; If the file already exists, the file will not be created and false will be returned

2. Get file or folder properties

Case 2 (common methods of obtaining files or folders)

package text;
import java.io.File;
public class FileDemo2 {
    public static void main(String[] args) {
        File f=new File("D:\\itcast\\java.txt");
        System.out.println(f.isDirectory());
        System.out.println(f.isFile());
        System.out.println(f.exists());
        System.out.println(f.getName());
        System.out.println(f.getAbsoluteFile());
        System.out.println(f.getPath());
        File f2=new File("D:\\itcast");
        String[] strArray = f2.list();
        for(String str:strArray){
            System.out.println(str);
        }
        System.out.println("---------");
        File[] fileArray = f2.listFiles();
        for(File file:fileArray){
          //  System.out.println(file);
            //System.out.println(file.getName());
            //Judge whether it is a file and only get the name of the file (the name of the directory will not be output)
            if(file.isFile()){
                System.out.println(file.getName());
            }
        }
    }

}


3. File or folder operation

Common methods:
1.public boolean renameTo(File newFile)(Rename file to newFile Corresponding file name)
2.public boolean delete()(Delete the current file. If the deletion is successful, return true,Otherwise return false)

4. Random access to files

1. For FileInputStream/FileOutputStream and FileReader/FileWriter, their instances are sequential access streams, that is, they can only read / write sequentially. The RandomAccessFile class allows the file content to complete read and write operations at the same time. It directly inherits the object and implements the interfaces DataInput and DataOutput at the same time.
2. RandomAccessFile provides methods to support random file operations:
(1) readXXX() or writeXXX(): such as ReadInt(),ReadLine(),WriteChar(),WriteDouble(), etc
(2) int skipBytes(int n): moves the pointer down several bytes
(3) length(): returns the length of the file
(4) long getFilePointer(): returns the current position of the pointer
(5) void seek(long pos): call the pointer to the desired position
When generating a random file object, you need to specify not only the file object and file name, but also the mode of accessing the file.
3. Construction method of RandomAccessFile:
RandomAccessFile(File file,String mode)
RandomAccessFile(String name,String mode)
4. Value of mode:
(1) r: read only. IOException will be thrown for any write operation
(2) rw: read / write. When the file does not exist, it will be created. If the file exists, the content of the original file will remain unchanged, and the file content will be changed through write operation.
(3) rws: open for reading and writing. For "rw", it is also required that each update to the file content or metadata be synchronously written to the underlying storage device.
(4) rwd: open for reading and writing. For "rw", it is also required that each update to the file content be synchronously written to the underlying storage device.

Case 3 (random access to files)

package text;
import java.io.IOException;
import java.io.RandomAccessFile;
public class  FileDemo {
public static void main(String[] args){
int data_arr[] = {12, 32, 43, 45, 1, 5};
   try {
         RandomAccessFile randf=new RandomAccessFile("temp.dat","rw");
            for(int i = 0; i < data_arr.length; i++){
                  randf.writeInt(data_arr[i]);
                }
             for(int i = data_arr.length-1 ; i >= 0; i--){
                  randf.seek(i * 4L);
                  System.out.println(randf.readInt());
              }
                randf.close();
            }catch(IOException e){
                System.out.println("File access error" + e);
            }
    }
}

2, Generics

1. The concept of generics

1. Generic, i.e. "parameterized type". When referring to parameters, the most familiar thing is that there is a formal parameter when defining the method, and then the arguments are passed when the method is called. Parameterized type is to parameterize the type from the original specific type, which is similar to the variable parameters in the method. At this time, the type is also defined as a parameter form (which can be called a type parameter), and then a specific type (type argument) is passed in during use / call.
2. The essence of generics is to parameterize types (without creating new types, the types of formal parameters are controlled by different types specified by generics). In other words, in the process of using generics, the data type of the operation is specified as a parameter. This parameter type can be used in classes, interfaces and methods, which are called generic classes, generic interfaces and generic methods respectively.

2. Generic classes and Applications

  1. Generic types are used in the definition of classes and are called generic classes. Through generics, you can complete the operation of a group of classes and open the same interface to the outside world.
    2. Definition of generic class: [modifier] class name < >

Case 1 (the simplest generic class application)

//Here, T can be written as any identifier. Common parameters such as T, E, K and V are often used to represent generics
//When instantiating a generic class, you must specify the concrete type of T
public class Text<T>{ 
    //key the type of this member variable is t, and the type of T is specified externally  
    private T key;

    public Generic(T key) { //The type of generic constructor parameter key is also t, and the type of T is specified externally
        this.key = key;
    }

    public T getKey(){ //The return value type of the generic method getKey is t, and the type of T is specified externally
        return key;
    }
}

Note: in the process of instantiating a generic class, the actual type must be a reference type. You cannot replace the parameter type with a basic type such as int, double or char to replace the type parameter T

3. Generic methods

Definition of generic method: to define a generic method, you only need to place the type parameter of the generic method in front of the return value type of the method

Case 2 (use of generic methods)

public class Text {
    private static int add(int a, int b) {
        System.out.println(a + "+" + b + "=" + (a + b));
        return a + b;
    }
 
    private static <T> T genericAdd(T a, T b) {
        System.out.println(a + "+" + b + "="+a+b);
        return a;
    }
 
    public static void main(String[] args) {
        GenericMethod1.add(1, 2);
        GenericMethod1.<String>genericAdd("a", "b");
    }
}
 

3, Container class

1. Container interface

1.1 Java container framework

1.2 container interface Collection

The Collection interface usually cannot be used directly, but it provides methods to add elements, delete elements and manage elements

1.3 List interface

List interface list is a Collection sub interface. It is a linear table containing ordered elements. The elements must be in order, repeatable, or null.
There are two main classes that implement the List interface: the linked List class LinkedLIst and the array List class ArrayList, both of which are linear tables

2. Set interface

Set is a Collection interface without duplicate elements. It inherits from the Collection interface and does not declare other methods. Its methods are inherited from the Collection interface

Posted by eflopez on Sat, 04 Dec 2021 10:15:22 -0800