Sorting out the content knowledge points of the JAVA final exam

author's words

Preface: These are very basic, and there are still many things that have not been written. The focus is on exam review, including the content of the last four chapters

For the previous content, please refer to the combing of the content and knowledge points of the JAVA stage test

1. Collection and flow

Class Summary 1 Collection

  • Collection concept:
    • A container object that holds and holds data, combining many elements into a single unit.
  • Collection framework:
    • The system for expressing and manipulating collections, including interfaces, implementation classes, and structure diagrams of collection frameworks.

4ede152b69a1475f945b23c974f34fbe.jpg

  • 接口:Iterable、Iterator、Collection、List、Queue、Set、Map;
  • 类:ArrayList,LinkedList,HashSet,TreeSet,HashMap,TreeMap,Stack;

Implementation:

  1.  java.lang.Iterable interface: implements the object of this interface class, supports the use of Iterable to traverse elements and supports For Each loop statement;
  2. boolean add(), add elements to the collection. If the call changes the set, return true, the same below
    1. next()//Move the cursor backwards and return the element pointed to by the cursor;
    2. remove()//Remove the unknown element of the current cursor;
  3. java.util.Collection interface: used to describe the most versatile collection, including the most versatile collection operations and methods;
    1. boolean add(), add elements to the collection. If the call changes the set, return true, the same below
    2. boolean addAll(), adds a collection to the collection
    3. boolean remove(), removes the specified element from the collection
    4. boolean removeAll(), removes the specified collection from the collection
    5. void clear(), remove all elements of the collection
    6. boolean contains(), to determine whether the collection contains the specified element
    7. boolean containsAll(), to determine whether to contain the specified collection
    8. boolean isEmpty(), to determine whether the collection contains elements
    9. int size() , the length of the collection
    10. T[] toArray(, convert the collection to an array of the specified type
    11. Iterator<E> iterator(), get iterator;
  4. java.util.List collection: an ordered collection of elements that can contain duplicates. In addition to the methods inherited from Collection, provide positional index-based operation methods:
    1. add(), move the specified position element back, add
    2. set(), replace
    3. get(int index), get
    4. remove(int index), remove
  5. The basic implementation class of the List collection interface, that is, the implementation of different data structures
    1. java.util.ArrayList, based on the realization of the object array data structure, the most used, the overall performance is good
    2. java.util.LinkedList, based on the implementation of the doubly linked list data structure
  6. Conversion of List and array:
    1. List to Array uses toArray() method;
    2. Array to List: The Arrays tool class provides the asList(T... a) method: the asList() method is an adapter mode method, only the type is converted, and the underlying layer is still an array. Therefore, executing any method that modifies the length of the collection (add/remove, etc.) will throw an exception

  7. java.util.Map interface: used to store key-value pairs (key-value), and obtain the corresponding value through the Key value
    1. The key in the Map must be unique, and each key can only correspond to one value; but different keys can correspond to the same value; when adding a key-value, if the key already exists, the latter will overwrite the previous one.
    2. Support any type (reference type) object as key/value
    3. Basic implementation class:
      1. java.util.HashMap, the most balanced query efficiency and memory usage, non-thread safe;
      2. java.util.TreeMap;
      3. java.util.Table
    4. Commonly used methods of operation:
      1. put(key, value), save the key-value pair
      2. get(key), get the corresponding value based on the key, if the value does not exist, return null
      3.  getOrDefault(key, VValue), get the corresponding value, if not, use the default value
      4. remove( key) , remove the corresponding value value
      5. containsKey(Object key), whether the key exists;
      6. containsValue(Object value), whether the value exists;
      7. size() , the length;
      8.  isEmpty(), whether it is empty;
    5. How to judge the same key? Rewrite the hashCode() and equals() methods

      String rewrites the hashCode()/equals() method, so it is directly based on the string value instead of the hash value comparison of the object (it seems to roughly mean that the judgment of key equality is based on the string value of the key directly based on the key)

  8. Set collection: does not contain repeated elements (abstraction of sets in mathematics) playing cards, non-repeating relationships, people, things, etc.

    Whether it is repeated: according to hashCode()/equals()

  9. Set interface: only includes the method inherited from Collection, and adds the restriction that duplicate elements are prohibited, and has no index-based operation method;
    1. Basic implementation class:

    2. java.util.HashSet<>, the elements are unordered (the bottom layer determines whether the elements are repeated based on HashMap)

    3. java.util.LinkedHashSet<>, the elements are ordered

    4. java.util.TreeSet<>, the elements are ordered

  10. An immutable collection is a collection that cannot be modified. After the definition is completed, it cannot be modified, or added or deleted. A collection's data items are provided at creation time and are immutable throughout their lifetime.

    In Java 9, you can use the static factory methods List.of, Set.of and Map.of to create immutable lists, sets or maps

Notice

 Class Summary 2 Stream

Functional programming is a programming idea

  1. Stream operates on the elements in the collection, not the collection itself. Therefore, new collections will be created to aggregate the results of Stream operations without affecting the source collection structure
  2. The basic steps to use Stream include:
    1. Create Stream: Obtain the data set of the collection object through the stream() method.
    2. Intermediate: Through a series of intermediate (Intermediate) methods, the data set is reprocessed such as filtering and retrieval. For example, use the filter() method to filter a dataset.
    3. Terminal: The processing of elements in the data set is completed through the final (terminal) method. For example, use forEach() to print the filtered elements
  3. Intermediate operation
    1. filter(): Filter out the elements that are inconsistent with the requirements, and put the elements whose expression result is true into the new stream
    2. map(): Map the type of elements in the stream to a new type, for example, as long as a certain attribute of the element

    3. sorted( Comparator .**): Sort the elements in the stream.

    4. Comparator . comparing() sorts based on the specified value,  reversed() reverses

  4. terminate operation
    1. collect(Collectors.**)

    2. The groupingBy() of Collectors returns Map, toList() , toSet() , toMap() according to the specified type and converts them into mapping relationships to give key and value

    3. forEach()

  5. After jdk8, map also has forEach() method, which is provided by map and not inherited

    forEach((k, v) -> { System.out.println(k + "/" + v.getColor());                });

  6. Element removal The removeIf() method of Collection is implemented based on Iterator.

Class Summary 3Optional Container

  1. Reason for introduction: Solve null pointer exception.
  2. Optional single-value container, providing many useful methods, without explicit null value detection when used
  3. Get the Optional object
    1. ofNullable() element does not have to be null
    2. of() element must not be empty//use less
  4. common method
    1. ifPresent(Consumer consumer) is not empty to perform parameter operations, and empty to do nothing
    2. The intermediate operation filter() filters and map is mapped to a new type of container. Both can return an empty container or () jdk9 method, execute the parameter function when it is empty, and must return the same type of container
    3. Termination operation: orElse(): Get the element type, return parameter creation object when it is empty,
      orEsleGet() execute function when empty, return element object
      get(), get container object, empty throw exception, not recommended, use orElse()
    4. isPresent() determines whether it is empty

Related exercises

1. The top-level interface of the Java collection framework is (C)

  • A. Iterable
  • B. Iterator
  • C. Collection
  • D. List

The Collection interface is the root interface of the Java collection framework, which defines a set of basic operations on objects, such as adding, deleting, clearing, traversing, and so on. The Iterable interface is a functional interface that has only one abstract method iterator()

2. Properly declare an integer collection variable (B)

  • A. List<int> list;
  • B. List<Integer> list;
  • C. List list<int>;
  • D. List list<T>;

3. If class A inherits from class B, it is allowed to add class B objects in the variable List<A> list1 collection

  • A. yes
  • B. Wrong

Because List<A> is a subclass of List, and List<B> is also a subclass of List, but there is no relationship between List<A> and List<B>. Therefore, only objects of type A can be added to the variable List<A> list1 collection, but objects of type B cannot be added

Supplementary questions

Class B inherits from class A, the collection List<A>, when adding an object of type B to the collection ( )

  • A. Compile-time errors
  • B. Runtime errors
  • c. Warning
  • D. no error

The parent class cannot be added, but the child class can be added

4.LinkedList is a linked list-based collection type inherited from the Collection interface

  • A. yes
  • B. Wrong

Answer analysis:

LinkedList is not a collection type, but an implementation of the List collection type based on a doubly linked list

5.Map is a collection type used to store key-value pairs

  • A. yes
  • B. Wrong

Map is not a collection

6. To construct an instance of the ArrayList class, which of the following statements is correct (B)?

  • A. ArrayList myList=new Object ();
  • B. List myList=new ArrayList ();
  • C. ArrayList myList=new List ();
  • D.List myList=new List();

7. Collection Stream is a container for operating collections

  • A. yes
  • B. Wrong

8. (True or false) Collection Stream can remove elements in the source collection through filtering operations

  • A. yes
  • B. Wrong

The operation of the stream will generate a new collection and will not affect the structure of the source collection

9. Optional is a collection type to which multiple objects of the same type can be added.

  • A. yes
  • B. Wrong

Optional is not a collection type, but a wrapper type used to represent a value that may or may not exist. It is generally used to handle the possibly null case, not for storing multiple objects. Optional types either contain a non-null value or are empty. If you want to represent multiple objects of the same type, you usually use List, Set, or other collection types.

10. Optional's map() method allows changing the type of elements in the container

  • A. yes
  • B. Wrong

The Optional class provides the map() method, which allows the values ​​in the Optional object to be converted and returns a new Optional object containing the result of the conversion. The function of the map() method is to convert the Optional object, which can change the type of elements in the container. This is very useful when dealing with Optional objects, converting an Optional object of one type to an Optional object of another type.

Two, abnormal

class summary

Exception classification:

  1. Throwable is the ancestor of all exceptions, Throwable has two subclasses, Error and Exception;
  2. Error is an error, indicating that a serious error has occurred in the running application, which is thrown through Error, and the general program cannot handle it;
  3. Exception is an exception, which means that when the program is running, the program itself can catch and handle errors;
  4. Common exceptions:

Keywords for exception handling:

  1. Catch the exception:
    1. try: Execute code that may generate exceptions;
    2. catch: catch exception;
    3. finally: Regardless of whether an exception occurs, the code is always executed;
  2. Throw an exception:
    1. Throw: In the exception generation phase, the exception object is manually thrown;
  3. Statement exception:
    1. throws declares various exception classes that the method may throw

 Define new exceptions:

  Common methods in the Throwable class:

Related exercises

1. Based on the following code, analysis method, no exception is thrown, the output result

private static void try() {

    try {

      System.out.println("A");

      method(); // 未引发异常

      System.out.println("B");

      return;

      System.out.println("C");

    } catch (Exception e) {

      System.out.println("D");

    } finally {

      System.out.println("E");

    }

    System.out.println("F");

    return;

  }
  • A. A B
  • B. A B E
  • C. A B E F
  • D. A E B

2. Based on the following code, analysis method, throwing an exception, the output result

private static void try() {

    try {

      System.out.println("A");

      method(); // 引发异常

      System.out.println("B");

      return;

      System.out.println("C");

    } catch (Exception e) {

      System.out.println("D");

    } finally {

      System.out.println("E");

    }

    System.out.println("F");

    return;

  }
  • A. A D E B
  • B. A D B E F
  • C. A D E F
  • D. A D E B C

3. Only supports custom Unchecked type exceptions, does not support custom checked type exceptions

  • A. yes
  • B. Wrong

Java supports custom checked type exceptions and unchecked type exceptions. A checked exception refers to an exception that must be handled when the program is compiled, while an unchecked exception refers to an exception that occurs only when the program is running. RuntimeException and its subclasses in Java are unchecked exceptions, and other Exceptions and their subclasses are checked exceptions

4. When customizing the exception class, the class that can be inherited is ( )

  • A. Error
  • B. Applet
  • C. Throwable, Exception and their subclasses
  • D. AssertionError

5. Regarding the arrangement of exceptions in the catch clause, which of the following is correct ( ) 

  • A. The parent class exception comes first, and the child class exception comes after
  • B. Subclass exceptions come first, parent class exceptions follow
  • C. Exceptions with inheritance relationship cannot be in the same try block
  • D. The exceptions can be arranged in any order, regardless of the order

This is because if the parent class exception comes first, then the subsequent subclass exceptions will not be caught, because the parent class exception already contains the subclass exception. And usually the information of the subclass exception is more precise than the parent class exception. So in order to correctly handle different types of exceptions, catch clauses should be arranged from small to large

6. The method that throws an exception is not declared in the parent class, and it is allowed to add a checked type exception declaration when the subclass is rewritten

  • A. yes
  • B. Wrong

When a subclass overrides the method of the parent class, for checked exceptions, the subclass cannot add a statement that throws an exception. The subclass can only throw exceptions declared in the parent class method or its subtype exceptions, or not throw exceptions at all. This is to ensure that the use of subclasses will not be more error-prone than parent classes, following the Liskov substitution principle.

If the method of the parent class does not declare to throw any checked exceptions, the subclass cannot declare to throw any checked exceptions when rewriting the method. If the method of the subclass throws a checked exception, the compiler will report an error. Only unchecked exceptions can be thrown without restriction in subclass methods.

7. When an exception occurs, java will search along the method call stack for the nearest program that specifically captures and handles the same type of exception, rather than a program that can handle this exception type

  • A. yes
  • B. Wrong

In Java, when an exception occurs, the Java virtual machine looks up the method call stack for a program that can handle the exception until it finds a suitable exception handler. This handler can be a program that specifically catches and handles this exception type, or it can be a general exception handler that can handle this exception type or its parent type.

The Java exception handling mechanism allows the use of try-catch statements to catch and handle exceptions. When an exception occurs, the program will jump to the catch block that can handle the exception, instead of continuing to look up the nearest program that specifically catches and handles the exception type. Therefore, an exception handler is not necessarily designed specifically for a certain exception type, but an exception handler capable of handling that exception type or its supertype.

So, the given statement is false. The correct expression should be: When an exception occurs, Java will look up the method call stack to find an exception handler that can handle the exception type or its parent type.

8. You can not catch and handle exceptions in the method where the exception occurs

  • A. yes
  • B. Wrong

In Java, exceptions can be caught and handled outside of the method where the exception occurred. The Java exception handling mechanism allows the use of try-catch statement blocks to catch exceptions and handle them in appropriate places. This means that you can use a try-catch statement to catch and handle exceptions where you call the method where the exception may occur, and you don't necessarily need to handle the exception inside the method where the exception occurred.

9. The method declaration throws an exception, which will affect the method signature

  • A. yes
  • B. Wrong

10. It is forbidden to throw exceptions on the constructor

  • A. yes
  • B. Wrong

In Java, constructors can throw exceptions. Like other methods, a constructor can include in its declaration a statement that it throws an exception.

Constructors can throw checked exceptions and unchecked exceptions. A checked exception is an exception explicitly declared in the method declaration that the caller must handle or continue to throw. An unchecked exception is an exception of RuntimeException or its subclasses that the caller can optionally handle or continue to throw.

When the constructor throws a checked exception, the caller must handle these exceptions when creating an object instance, and can catch the exception through a try-catch block or continue to throw an exception to the upper layer.

11. Abstract methods cannot be declared to throw exceptions

  • A. yes
  • B. Wrong

An abstract method is a method that has no concrete implementation, it is just declared in an abstract class or interface. In Java, abstract methods can be declared to throw exceptions, just like ordinary methods. The purpose of declaring that an exception is thrown is to let the caller know that the method may generate a specific type of exception and take corresponding measures.

12. When interacting with external resources, Unchecked type exceptions may occur

  • A. yes
  • B. Wrong

When interacting with external resources, checked exceptions may occur instead of unchecked exceptions (Unchecked Exception). Unchecked exceptions (such as RuntimeException and its subclasses) usually indicate program errors or programming errors, while checked exceptions (such as IOException, SQLException, etc.) usually indicate failures or abnormal conditions of external resource operations.

Three, thread

class summary

program, process, thread

  • Program: refers to a file containing instructions and data, which is stored on a disk or other data device, that is to say, a program is a static code;
  • Process: It is an execution process of a program, a running activity of code on a data set, and the basic unit of system resource allocation and scheduling;
  • Thread: A thread is an entity in a process, and is the basic unit independently scheduled and dispatched by the system. There is at least one thread in a process, and multiple threads in a process share the resources of the process;

In short, a program has at least one process, and a process has at least one thread

Thread creation:

Inherit the Thread class to create threads

 Implement the Runnable interface to create threads

 order of execution

 Common methods of the Thread class:

  • start(): Start a new thread and execute  run() the code in the method.
  • run(): Defines the code to be executed by the thread.
  • sleep(long millis): Make the current thread suspend execution for the specified time.
  • join(): Wait for this thread to terminate.
  • interrupt(): Interrupt the thread.
  • The function of notify() and notifyAll() is to wake up the waiting thread on the current object; notify() wakes up a single thread, and notifyAll() wakes up all threads.

  • wait() : The function is to let the current thread enter the waiting state, and at the same time, wait() will also let the current thread release the lock it holds. until another thread calls this object's

Synchronization of threads:

volatile keyword:

Simple, guaranteed data visibility. That is, when a thread changes a certain piece of data in the main memory, it will be refreshed to the main memory immediately after the modification. And it will force the data in the thread that cached the variable to be cleared, and the latest data must be read from the main memory again .

Volatile can guarantee the visibility of variables, but cannot guarantee the atomicity of concurrent execution operations

synchronized keyword

It is used to decorate methods or code blocks. When a method or code block is declared as synchronized, it means that this method or code block is synchronized and can only be accessed by one thread at the same time.

The synchronized keyword can ensure thread safety and prevent multiple threads from accessing and modifying shared data at the same time. When a thread enters a synchronized method or code block, it acquires a lock; when the thread leaves the synchronized method or code block, it releases the lock. Only the thread that acquires the lock can enter the synchronized method or code block,

The constructor cannot be synchronized, it is a syntax error to use the synchronized keyword in the constructor

Synchronized cannot modify abstract methods

Related exercises

1. The method in the CountDownLatch class that requires the execution thread to block until the counter is zero is

  • A. trace()
  • B. await()
  • C. sleep()
  • D. submit()

CountDownLatch is a synchronization auxiliary class in Java, which can be used to control one or more threads to wait for the completion of other threads' operations. It is implemented with a counter that is initialized to a positive integer and until the counter reaches zero the calling thread is blocked.

The await() method is a method used to block threads in the CountDownLatch class. When the await() method is called, the current thread is blocked until the value of the counter becomes zero. When other threads call the countDown() method of CountDownLatch, the value of the counter will be reduced by one, until the value of the counter is zero, the blocked thread will be awakened to continue execution.

2. Regarding the keyword volatile, which of the following statements is correct

  • A.  It can be guaranteed that the operation of the modified variable is synchronized
  • B.  Modification methods to achieve atomic operations
  • C.  The thread does not save a copy of the variable, and reads it from the main memory every time it is used
  • D.  Only supports modification of basic data types

The keyword volatile is used to modify variables in Java, and has the following characteristics:

A. It can ensure that the operation on the modified variable is visible, that is, when a thread modifies the value of the variable modified by volatile, other threads can immediately see the latest value. But it does not guarantee the atomicity of operations, so it is not suitable for guaranteeing the synchronization of operations on variables.

B. Modified methods cannot achieve atomic operations. The volatile keyword is mainly used to modify variables, not methods.

C. The thread does not save a copy of the volatile modified variable, and reads the latest value from the main memory every time the variable is used. This is an important feature of volatile, which ensures that the thread gets the latest value.

D. The volatile keyword not only supports modifying basic data types, but also supports modifying reference type variables. Therefore, option D is incorrect.

4. Issue an interrupt notification, which will stop the thread from running

  • A. yes
  • B. Wrong

Issuing an interrupt notification does not directly stop the thread from running. In Java, you can use the interrupt () method of the Thread class to issue an interrupt notification, but this is only a notification mechanism, which will set the interrupt status of the thread, and will not directly stop the execution of the thread.

5. By default, the thread will execute the task repeatedly until it is forcibly interrupted

  • A. yes
  • B. Wrong

By default, a thread does not loop over and over again until it is forcibly interrupted. The execution of a thread depends on the tasks performed by the thread and the logic of the thread.

In Java, a thread can perform a one-time task or a cyclic task, depending on the implementation code of the thread. A thread can end itself when a task is complete, or when a condition is met or an interrupt notification is received.

6. There are two instance-level methods that require synchronization in the class. When one thread calls one of the synchronization methods, other threads cannot call the other synchronization method.

  • A. yes
  • B. Wrong

7. There is 1 instance-level method in the class that requires synchronization, and 1 ordinary method.

When 1 thread calls one of the synchronized methods, other threads cannot call the non-synchronized method

  • A. yes
  • B. Wrong

8. The running result of the following program ()

public static void main(String[] args) {

Thread t = new Thread() {

public void run() {

pong();

}

};

t.run();

System.out.print("ping");

}



static void pong() {

System.out.print("pong");

}
  • A. pingpong
  • B.  pongping
  • C. Both pingpong and pongping are possible
  • D. neither

9. The following interfaces that can implement atomic execution operations under multi-threading are ( )

  • A. Lock
  • B. Random
  • C. Atomic
  • D. Executor

10. Both the sleep() method and the wait() method of the Thread class can make the thread suspend execution.
A. Right
B. Wrong

Both the sleep() method and the wait() method of the Thread class can suspend the execution of the thread, but their usage and effects are different.

The sleep() method is a static method of the Thread class. Calling it will cause the current thread to suspend execution for a specified period of time. The sleep() method will not release the lock, and the thread will not be interrupted during the sleep period, and will not continue to execute until the sleep time is over.

The wait() method is an instance method of the Object class. Calling it will cause the current thread to suspend execution and release the lock on the object. The wait() method is usually used with the synchronized keyword to achieve coordination and synchronization between threads. When a thread calls the wait() method, it enters the waiting state until other threads call the notify() or notifyAll() method of the same object to wake up the waiting thread.

Four, IO operation

class summary

The concept of IO stream:

  • IO streams operate read() and write() in the same way for different input and output; creating different types of streams has different implementation methods, and different types of streams have their own unique operation methods.
  • Regardless of how it works internally, all IO streams present the same, simple pattern, a sequence of data flowing in or out of a program.

Inputstream、Outputstream:

  • Input stream, the operation superclass of output stream, supports subclasses to operate binary data in the form of basic bytes
  • java.io.InputStream abstract class: basic subclasses, ByteArrayInputStream, FileInputStream, etc.; 
  • int read() throws IOException, the abstract method is implemented by specific subclasses, and returns the next byte in the stream (must be represented by an integer between 0-255), if there is no readable byte at the end of the stream, return -1.
  • java.io.OutputStream abstract class: basic subclasses, ByteArrayOutputStream, FileOutputStream, etc.;
  • void write(int b) throws IOException Abstract method. Write the decimal byte-wise to the output stream.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
 
public class TestIO {
    public static void main(String[] args) {
        try {
            getByteStreams();
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
    public static void getByteStreams()throws IOException {
        FileInputStream in=new FileInputStream("C:/Users/yu/Desktop/a.txt");
        FileOutputStream out=new FileOutputStream("C:/Users/yu/Desktop/b.txt");
        int c;
        while((c=in.read())!=-1){
            System.out.println("读取字节的10进制整数:"+c);
            out.write(c);
        }
        in.close();//有个问题就在于一旦异常了资源就无法关闭;
        out.close();
    }
 
}
  • Closing of resource files: Resource files, such as IO streams, will not automatically release resources occupied by losing references like other objects. Therefore, they must be closed correctly, otherwise it will cause memory overflow. Taking IO streams as an example, to ensure Regardless of whether an exception occurs, the resource is closed, and the resource should be closed manually in the finally block, but this will cause a lot of redundancy in the program;

The try-with-resources statement greatly simplifies the resource processing code, so that developers do not need to care about the status of resources, the order in which resource objects are created, or the correct closing method of resource objects

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class Main {
    public static void main(String[] args) {
        getByteStreams();
    }
 
    public static void getByteStreams() {
        // 使用try-with-resources语句来创建输入流和输出流
        try (FileInputStream in = new FileInputStream("D:/桌面/in.txt");
             FileOutputStream out = new FileOutputStream("D:/桌面/out.txt")) {
            int c;
            while ((c = in.read()) != -1) {
                System.out.println("读取字节的10进制整数:" + c);
                out.write(c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

  • Notice:

    (1) The automatic closing of resources has nothing to do with exceptions. How to deal with the exception is still how to deal with it.

    (2) After declaring the use of resources in the try statement, the execution sequence:

    • ​​​​No exception, after the try block is executed, the resource is automatically closed, the finally block

    • There are exceptions, resources are automatically closed, catch blocks, finally blocks

path:

  • An absolute path, always including the root element and the full directory listing needed to find the file. For example, D:/test/a.txt. All the information needed to find the file is contained in the path declaration

  • A relative path, for example, a.txt. The program will not be accessible without further information. That is, relative paths must ultimately be described based on absolute paths. '

  • Path interface: Path represents a file path that does not depend on the system. That is, the specific implementation of Path is different (windows/linux) when running under different operating systems, but developers only need to describe paths for Path, and do not need to care about differences in operating systems for different systems.

  • Path getFileName(), returns the filename or the last element of a sequence of name elements. That is, the last path description, which may be a file name or a directory name

    Path getParent(), returns the path of the parent directory

  • Path getRoot(), returns the root of the path

    Path resolve(Path other) method, splicing paths into a new path

    boolean equals(Object obj): Override equals to determine whether the paths are the same

Files tool class:

  • The java.nio.file.Files tool class provides a wealth of static methods based on Path operations, read/write/operate, files and directories. Method classification:

  • Judgment of files or directories:

    boolean exists(Path path)/notExists(Path path), whether the Path path exists

    Boolean isDirectory(Path path), whether path is a directory

  • Creation of files or directories:

    Path createDirectory(Path dir) throws IOException. It is abnormal if the directory path already exists; if the directory path is a multi-level directory, it is abnormal

    Path createDirectories(Path dir) throws IOException. Automatically create multi-level non-existing directories; directory already exists, no exception

    Path createFile(path) throws IOException. Create a file based on the specified path. file exists, exception

  • Copying of files or directories:

    Path copy(Path source, Path target, CopyOption... options) throws IOException, copy the file to the target file. By default, if the file already exists, an exception

    If the source is a directory, the files inside will not be copied, it is only equivalent to creating an empty directory

    java.nio.file.StandardCopyOption enumeration, implements the CopyOption interface, copy options

  • File or directory movement:

    Path move(Path source, Path target, CopyOption... options) throws IOException, move or rename the file to the target file.

    By default, if the target file exists, it will be an exception, and the move option can be declared through the options parameter

    If you move in this directory, it is equivalent to renaming the file

  • File or directory deletion:

    void delete(Path path) throws IOException. Delete the specified path; path does not exist, exception

    boolean deleteIfExists(Path path) throws IOException. The path does not exist and is not deleted. Return whether the deletion is successful

    If the path is a directory, and the directory contains files (that is, not empty), both deletions are abnormal

  • Traversal of the specified path (Files method):

    Stream<Path> walk(Path start, int maxDepth) throws IOException: Traversing, traversing directories and files in the path path based on the specified depth

    Stream<Path> walk(Path start) throws IOException: traverse all directories and files in the path path, including subdirectories, observe the output order during traversal, and output them hierarchically. Note that the return value is a stream, and stream operations can be used later, such as filtering, sorting and other functions. You can delete non-empty directories with the help of this method

Related exercises

1. The following can be correctly described, C:/a/b, the output of the path is

String p1 = "C:/";
String p2 = "a";
String p3 = "b";

  • A. System.out.println(p1 + p2 + p3);
  • B. System.out.println(Path.of(p1 + p2 + p3));
  • C. System.out.println(Path.of(p1).resolve(p2).resolve(p3));
  • D. System.out.println(Path.of(p3).resolve(p2).resolve(p1));

The correct output is:

C.System.out.println(Path.of(p1).resolve(p2).resolve(p3));

This code will combine the path as "C:/a/b" and output. The Path.of() method is used to create a path object, and the resolve() method is used to connect path segments.

2. If an exception is thrown in the try code block of the try-with-resources statement, first execute the catch block to handle the exception and finally block, then close the resource

  • A. yes
  • B. Wrong

3. The read(byte[] b) method of InputStream, when the number of bytes in the stream exceeds the capacity of the byte array buffer, an exception will be thrown

  • A. yes
  • B. Wrong

When using the InputStream's read(byte[] b) method, this method does not throw an exception if there are more bytes in the stream than the byte array buffer can hold. It reads as much data from the stream as possible into the byte array buffer and returns the number of bytes actually read. If the number of bytes in the stream exceeds the buffer's capacity, it will only read the buffer's size of bytes, and return that many. The remaining bytes will remain in the stream, available for subsequent read operations.

4. The write(byte[] b) method of OutputStream will write all the bytes in the byte array buffer to the output stream

  • A. yes
  • B. Wrong

When using the write(byte[] b) method of OutputStream, all bytes in the byte array buffer are written to the output stream. Specifically, this method writes all the bytes in the byte array b to the output stream so that the data can be sent to the destination. If the length of the byte array is greater than the output stream's buffer size, this method writes all the bytes to the output stream's buffer, sending as many of the buffer's contents as possible to the destination.

5. By default, the input and output streams are based on character strings to complete file operations
A. True
B.  False

By default, input and output streams do not perform file operations based on strings. Input and output streams (InputStream and OutputStream) are used for byte-level input and output operations. They are used to work with byte data rather than string data.

Guess you like

Origin blog.csdn.net/qq_62377885/article/details/130780733