今天,我们将研究Java文件路径,Java文件路径可以是抽象的,绝对的或定义的。
Java 文件路径
「java.io.File」包含三种方法来确定文件路径,我们将在本教程中探索它们。
- " GetPath() " : 此文件路径方法返回抽象路径名为 String. 如果字符串路径名用于创建文件对象,那么它只是返回路径名参数. 如果URI被用作参数,则它会删除协议并返回文件名. (_) )2. `Get AbutePath ()': 此文件路径方法返回文件的绝对路径 。 如果文件是用绝对路径名创建的,它只是返回路径名. 如果使用相对路径创建文件对象,则绝对路径名以系统依赖的方式解决. 在UNIX系统中,相对路径名通过对照当前用户目录进行解析而成为绝对. 在Microsoft Windows系统上,相对路径名通过对照路径名命名的驱动器当前目录(如果有的话)解决而变得绝对;如果有的话,则根据当前用户目录解决.
- `[Get CanonicalPath] (https://docs.oracle.com/javase/7/docs/api/java/io/File.html#getCanonicalPath( ()': 这种路径方法返回绝对而独特的犬形路径名. 这种方法首先在必要情况下将这个路径名转换为绝对形式,仿佛通过引用取自"Geat AbsolutePath"方法,再以系统依赖的方式将它映射到它的独特形式. 这通常涉及从路径名中去除""和"."等冗余名称,解决符号链接(在UNIX平台上),将驱动字母转换为标准大小写(在Microsoft Windows平台上). (单位:千美元) (英语)
Java 文件路径示例
让我们用一个简单的程序来看看Java中的文件路径的不同案例。
1package com.journaldev.files;
2
3import java.io.File;
4import java.io.IOException;
5import java.net.URI;
6import java.net.URISyntaxException;
7
8public class JavaFilePath {
9
10 public static void main(String[] args) throws IOException, URISyntaxException {
11 File file = new File("/Users/pankaj/test.txt");
12 printPaths(file);
13 // relative path
14 file = new File("test.xsd");
15 printPaths(file);
16 // complex relative paths
17 file = new File("/Users/pankaj/../pankaj/test.txt");
18 printPaths(file);
19 // URI paths
20 file = new File(new URI("file:///Users/pankaj/test.txt"));
21 printPaths(file);
22 }
23
24 private static void printPaths(File file) throws IOException {
25 System.out.println("Absolute Path: " + file.getAbsolutePath());
26 System.out.println("Canonical Path: " + file.getCanonicalPath());
27 System.out.println("Path: " + file.getPath());
28 }
29
30}
Below image shows the output produced by the above java file path program. The output is self-explanatory. Based on the output, using the canonical path is best suitable to avoid any issues because of relative paths. Also, note that the java file path methods don't check if the file exists or not. They just work on the pathname of the file used while creating the File object. That's all for different types of the file path in java.
您可以从我们的 GitHub 存储库中查看更多 Java IO 示例。