java中几种不同文件路径的区别(绝对路径,全路径)
java中几种不同文件路径的差别(绝对路径,全路径)
package com.tij.io.file; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; /** * 学习java中几种表示文件路径的方法差别 * @author guoyoujun * @date 2014-3-17 */ public class JavaFilePath { /** * java.io.File类中包含了三个方法来确定一个文件的路径 * <p>getPath(): 这个方法返回的是文件的抽象路径的一段字符串,如果使用这个抽象路径来创建一个file对象,那只是单纯的返回一个路径名 * 如果用作URL使用,则去除掉http协议头返回一个路径名 * <p>getAbsolutePath():这个方法返回文件的绝对路径,如果文件是以绝对路径创建的则返回绝对路径名,如果是相对路径创建的,则要考虑系统相关性 * 在unix系统中,相对路径名是以当前用户的目录为绝对路径的,在window系统中相对路径是以当前磁盘为绝对路径 *<p>getCanonicalPath():这个方法是获取文件完整路径的唯一方法,获取路径的时候会先转成文件的绝对形式,然后会根据系统相关性(window,unix)来获取路径 * @param args * @throws IOException * @throws URISyntaxException */ public static void main(String[] args) throws IOException, URISyntaxException { File file = new File("/Users/GYJ/java1.txt"); printPaths(file); //relative path(相对路径) file = new File("NewDB.properties"); printPaths(file); //complex relative paths(复杂点的相对路径) file =new File("/Users/../GYJ/funshion/bbinfo.txt"); printPaths(file); //URI paths(URL) file =new File(new URI("file:///Users/GYJ/java1.txt")); printPaths(file); } private static void printPaths(File f) throws IOException { System.out.println("AbsolutePath = " + f.getAbsolutePath()); System.out.println("CanonicalPath = " + f.getCanonicalPath()); System.out.println("Path = " + f.getPath()); } } out put============ AbsolutePath = C:\Users\GYJ\java1.txt CanonicalPath = C:\Users\GYJ\java1.txt Path = \Users\GYJ\java1.txt AbsolutePath = C:\Users\GYJ\workspace\java_workspace\io\NewDB.properties CanonicalPath = C:\Users\GYJ\workspace\java_workspace\io\NewDB.properties Path = NewDB.properties AbsolutePath = C:\Users\..\GYJ\funshion\bbinfo.txt CanonicalPath = C:\GYJ\funshion\bbinfo.txt Path = \Users\..\GYJ\funshion\bbinfo.txt AbsolutePath = C:\Users\GYJ\java1.txt CanonicalPath = C:\Users\GYJ\java1.txt Path = \Users\GYJ\java1.txt