Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Several common methods of obtaining file path in java

Shulou Source: shulou.com Published: 2022-06-02 08:48:54 10月03日 Update

This article mainly explains "java several common methods to obtain file paths", the explanation content in the article is simple and clear, easy to learn and understand, please follow the small series of ideas slowly in-depth, together to study and learn "java several common methods to obtain file paths" bar!

There are several common ways to get file paths in Java. Here are some examples of how to use them and how they work.

The directory structure of test items is shown in the right figure:

1. Use the File class

File file = new File("");// Java projects-->D:\WorkSoftware\Workspace\Eclipse Projects\MyWorkspace\test// Web projects-->D:\WorkSoftware\Server\apache-tomcat-7.0.96\binSystem.out.println(file.getAbsolutePath());File file = new File("/");/ Java projects--> D: \/ Web projects-->D:\System.out.println(file.getAbsolutePath());

2. Use of environmental variables

String path = System.getProperty("user.dir");// Java projects-->D:\WorkSoftware\Workspace\Eclipse Projects\MyWorkspace\test/Web projects-->D:\WorkSoftware\Server\apache-tomcat-7.0.96\binSystem.out.println(path);

3. Use the class loader

String path = MyTest.class.getResource("").getPath();// Java project-->D:/WorkSoftware/Workspace/Eclipse Projects/MyWorkspace/test/target/classes/com/luther/test//// Web project-->D: The requested URL/webapps/test/WEB-INF/classes/com/luther/test/System.out.println(path) was not found on this server. String path = MyTest.class.getResource("/").getPath();// Java project-->D:/WorkSoftware/Workspace/Eclipse Projects/MyWorkspace/test/target/classes//// Web project-->D: The requested URL/webapps/test/WEB-INF/classes/System.out.println(path) was not found on this server. String path = MyTest.class.getClassLoader().getResource("").getPath();// Java project-->D:/WorkSoftware/Workspace/Eclipse Projects/MyWorkspace/test/target/classes//// Web project-->D:/WorkSoftware/Server/apache-tomcat-7.0.96/webapps/test/WEB-INF/classes/System.out.println(path);

summary

In Java and Web environments, it is best to use class loading to find files, which is better.

Thank you for reading, the above is "java several common methods to obtain file path" content, after the study of this article, I believe we have a deeper understanding of java several common methods to obtain file path this problem, the specific use of the situation also needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!

Tags: Projects files common methods paths environment learning content writing variables right chart that is ideas situations effects articles ways more best directories Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB MySQL Microsoft OPPO Reno Apple