(File operation) File class operation in-depth

File class operation in-depth

  • In the actual software project development and operation, the project development is often carried out in the windows system, and the Linux or Unix system is used to release the project when the project is deployed to ensure the safety of the project production link;
  • In different operating systems, there will be different path separators "\" and Linux separators "/", so in the initial development, the separator problem under different system environments must be considered in order to solve this problem , The File class provides a constant: public static final String separator;

Example: Normal path writing

 File file = new File("F:"+File.separator+"Test"+File.separator+"test.txt"); //File.separator表示分隔符

However, as the adaptability of the system continues to strengthen, the current path operation can also be used at will (no distinction / \).

When using the File class for file processing, you need to pay attention to: Program -> JVM -> Operating System Functions -> Disk File Processing, so there may be a delay problem when the same file is repeatedly deleted or created.

There is an important premise when creating a file: the parent path of the file must first exist .

Get the parent path: public File getParentFile();

Create a directory: public boolean mkdirs() or mkdir; (create multi-level directories and single-level directories)

public static void main(String[] args) throws IOException {
        File file = new File("F:"+File.separator+"Test"+File.separator+"test.txt"); //File.separator表示分隔符
        if(!file.getParentFile().exists()){     //判断父路径是否存在
            file.getParentFile().mkdirs();  //创建父路径
        }
        if(file.exists()){  //文件存在
            file.delete();  //删除文件
        }else{  //文件不存在
            System.out.println(file.createNewFile());   //创建文件
        }
    }

This operation of judging the parent directory may only need to be done once in many cases, but if this judgment stays in the code all the time, it will increase the time complexity, so if you want to improve the performance of the heart, you must first ensure that the directory has been created.

Guess you like

Origin blog.csdn.net/weixin_46245201/article/details/112756185