Java learning record Day16 (abnormal, File class)

Day 16

May 12, 2019.
This is the sixteenth day I learn Java.
On this day, I learned the following knowledge.

abnormal

An exception is a Java program errors occur during operation

Throwable: the problem, the parent class

Several common methods are as follows:

  • getMessage()Gets the exception message, return the string
  • toString()Gets exception classes and exceptions, which returns the string
  • printStackTrace()Gets the exception class name and exception information, as well as locations of the anomalies in the program. Return value void

Error: error, belongs to the seriousness of the problem, such as memory overflow, can not handle

Exception: Abnormal, divided into:

  • The compiler exception: non RuntimeException and its subclasses, have to deal with, or can not run
  • Runtime exception: RuntimeException and other subclasses

Interview questions: JVM default is how to handle the exception?
When the main function receives this issue, there are two approaches:
A: own deal with the issue, and then continue running
b: for he did not approach, only to call the main jvm to handle
jvm have a default exception handler mechanism, it is the abnormal processing.
and the name of the exception, the exception information. abnormal position of the print on the console, and the program will stop running

Exception handling of two ways:

  • try…catch…finally
    • The basic format:
try	{
		可能出现问题的代码 ;
	}catch(异常名 变量名){
		针对问题的处理 ;
	}finally{
		释放资源;
	}
  • Deformation format:
//格式1
try	{
			可能出现问题的代码 ;
		}catch(异常名 变量名){
			针对问题的处理 ;
		}
		
//格式2
try {

			可能出现问题的代码 ;
		}catch(异常名1 变量名1){
			对异常的处理方式 ;
		}catch (异常名2 变量名2){
			对异常的处理方式 ;
}....

//格式3
try	{
			可能出现问题的代码 ;
		}catch(异常名 变量名){
			针对问题的处理 ;
		}finally{
			释放资源的处理 ;
		}
  • Note:. 1.try code as little as possible, and do catch the process, even if it is an output statement can be (can not be an exception information hiding)
    2. Can clear as clear as possible, not used to handling large. And the anomaly does not matter who is who, after former same level of relationship, if the child-parent relations, the parent must be behind the
    3 finally Keywords: controlled finally seeing the body will perform for the release of resources in the IO stream operations and database operations We will see
    4Interview questions: the difference between final, finally and finalize the

    • final: is a state of modifier can be used to decorate a class, variable, members of the methods
      modified class can not be inherited by subclasses, modified variable is actually a constant that can not be re-assignment
      method can not be overridden by subclasses modified
    • finally: try ... catch ... used in the statement, action: releasing resources Features: Always be executed (JVM can not exit)
    • finalize: a method Obejct class, for garbage

    5 Interview questions: If you catch a return statement there, what finally code will execute if you will, what is still return before the return?
    Solution: will be executed before return

  • throws
    when defining the function method, you need to be exposed so that the problem of the caller to deal with.
    Then identified on the method throws.
    Format: 修饰符 方法名 throws 异常名{ }
    There is also a keyword throw, the difference between it and throws are:

    • throw: throw an exception, this is abnormal must have happened, for use in the method of internal thrown exception object is thrown, you can only throw a
    • throws: thrown exception, is likely to occur, the method used in the statement, an exception is thrown by the class name, you can throw more

Notes throws the exception:

  1. Subclass the parent class method when rewriting, the parent class method had not thrown an exception, then the subclass can not throw an exception, there is an exception if the subclass can only capture (with a try ... catch)
  2. The parent class methods throws an exception, then the subclass can throw with the same parent class exception can be thrown smaller than the parent class exception
  3. Subclass can not throw the father had not thrown exceptions

Custom exception:

Later in the development process, we may encounter a variety of problems. JDK is impossible and for each given specific issues corresponding exception class. To meet demand, we need to custom exception.

To use a custom exception, we need to need our custom exception class definition into our system anomalies

This class inherits from Exception, or inherit from RuntimeException

Code Example: test scores must be between 0-100, it does not meet an exception

1. ScoreException custom exception class code as follows:

public class ScoreException extends RuntimeException{
    public ScoreException(String msg) {
        super(msg);
    }
}

2. Test class MyTest an example:

public class MyTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你的考试成绩,范围是 0--100");
        int score = scanner.nextInt();
        test(score);
    }

    private static void test(int score) {
        if (score > 100 || score < 0) {
            throw new ScoreException("成绩不合法");
        } else {
            System.out.println(score);
        }
    }
}

File type

File, is an abstract representation of the Java program file and directory path names

Constructors:File(String pathname) :File objects obtained according to a path
File(String parent, String child)According to a File object to get a sub-directory and file / directory
File(File parent, String child)According to a File object to get a File object parent and a child file / directory

Members of commonly used methods

  • Creating function

    • public boolean createNewFile()Create a new file, if such a file exists, you do not create a
    • public boolean mkdir()Create a folder, if there is such a folder is not created, note that this method can only create the flat directory, if the directory was created layer by layer to create multilayer
    • public boolean mkdirs()Create a folder, if the parent folder does not exist, it will help you create, you can create a multi-layer directory, of course, you can create a flat directory
    • Note: There is no written letter path when you create a file or folder, the default will be created in the project path. In general, the project was best to use relative path (the path without the disk symbol), not an absolute path (path with detailed disk symbol)
  • Delete function

    • public boolean delete()To delete a file or folder
      - When you delete a folder, this folder must be empty folder. If this folder there are files can not be deleted
      - to delete Java does not go the Recycle Bin
  • Rename function

    • public boolean renameTo(File dest)Rename the file to a specified file path
      - If the same path name is renamed. If the pathname is different, it is renamed and cut.
  • Judgment function

    • public boolean isDirectory()To determine whether a directory
    • public boolean isFile()Determine whether the file
    • public boolean exists()Determine whether there
    • public boolean canRead()It determines whether or not readable
    • public boolean canWrite()Determine whether writable
    • public boolean isHidden()To determine whether hidden
    • public boolean isAbsolute()Determine whether to use an absolute path
  • Acquisition function

    • public String getAbsolutePath()Gets the absolute path
    • public String getPath()Get the relative path
    • public String getName()Get the name of
    • public long length()Get the length. Byte count
    • public long lastModified()Acquiring last modification time, milliseconds
    • public String[] list()Get the name of an array of all files or files in the specified directory folder
    • public File[] listFiles()File obtain an array of all files or files in the specified directory folder
  • File filters

    • public String[] list(FilenameFilter filter)It returns an array of strings, these strings pathname of the directory designated by this abstract representation that satisfy the specified files and directories in the filter
    • public File[] listFiles(FilenameFilter filter)Returns the abstract pathname array of directory pathname of this abstract pathname that satisfy the specified filter files and directories
      File class classical algorithm
  • Traversing File
    demand: Are there any extension of .jpg files in the specified directory to determine the D drive, and if so, to output the file name of the
    code is as follows

public class MyTest {
    public static void main(String[] args) {
        File file = new File("D:\\test");
        File[] files = file.listFiles();
        for (File f : files) {
           if(f.isFile()&&f.getName().endsWith(".jpg")){
               System.out.println(f.getName());
           }
        }
    }
}
  • Traversing the filter used as the file
    needs: using file name filter mode, determines whether the file extension .jpg disk D specified directory, and if so, outputs the absolute file path
    code is as follows
public class MyTest {
    public static void main(String[] args) {
        File file = new File("D:\\test");
        File[] files = file.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if(pathname.isFile()&&pathname.getName().endsWith(".jpg")){
               		System.out.println(pathname.getAbsolutePath());
                    return  true;
                }else{
                    return false;
                }
            }
        });
        for (File file1 : files) {
            System.out.println(file1);
        }
    }
}
  • Traversing the file and modify the file name
    needs: modify the names of all files in the specified directory
    , such as:
    E: \ Resource \ all kinds of tyranny [www-itcast-cn] cures all kinds of pain 01.mp4
    E: \ Resource \ various special treatment [www-itcast-cn] cures all kinds of pain 02.mp4
    E: \ resource \ various cures [www-itcast-cn] cures of various pain 03.mp4
    ...
    modified to
    E: \ resource \ various cures \ cures various pains 01.mp4
    E: \ Resource \ various cures \ cures all kinds of pain 02.mp4
    E: \ Resource \ various cures \ cures of various pain 03.mp4
    ...
    code is as follows
public class Test {
    public static void main(String[] args) {
        File file = new File("E:\\resource");
        File[] files = file.listFiles();
        for (File f : files) {
            if(f.isFile()&&f.getName().startsWith(".[www-itcast-cn]")){
                String a = f.getName().replace("[www-itcast-cn]", "");
                File file2 = new File("E:\\resource",a);
                f.renameTo(file2);
                System.out.println(file2.getName());
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_41151659/article/details/90244426