标签:
1.先看下四个静态变量
static String |
pathSeparator
The system-dependent path-separator character, represented as a string for convenience.
|
static char |
pathSeparatorChar
The system-dependent path-separator character.
|
static String |
separator
The system-dependent default name-separator character, represented as a string for convenience.
|
static char |
separatorChar
The system-dependent default name-separator character.
|
由于windows和unix内核的系统路径表示方式不一致(windows为‘\‘,unix内核的为‘/‘),所以java提供了公用的路径分割符,根据不同的系统自动变换,但是在实际使用中,都使用‘/‘,windows和unix内核系统都支持。
Linux下测试
public class FileTest { public static void main(String[] args) { System.out.println(File.pathSeparator); System.out.println(File.pathSeparatorChar); System.out.println(File.separator); System.out.println(File.separatorChar); } }
输出
:
:
/
/
2.File类的构造方法
File(File parent, String child)
Creates a new
File instance from a parent abstract pathname and a child pathname string. |
File(String pathname)
Creates a new
File instance by converting the given pathname string into an abstract pathname. |
File(String parent, String child)
Creates a new
File instance from a parent pathname string and a child pathname string. |
File(URI uri)
Creates a new File instance by converting the given file: URI into an abstract pathname.
|
第一种
@Test public void test1() throws Exception{ File parent = new File("/joey/soft"); File son = new File(parent,"son.txt"); System.out.println(son.getAbsolutePath()); System.out.println(son.getParent()); System.out.println(parent.getName()); }
输出
/joey/soft/son.txt
/joey/soft
soft
第二种
@Test public void test2() throws Exception{ File son = new File("/joey/soft/son.txt"); System.out.println(son.getAbsolutePath()); System.out.println(son.getParent()); }
输出
/joey/soft/son.txt
/joey/soft
第三种
@Test public void test3() throws Exception{ File son = new File("/joey/soft","son.txt"); System.out.println(son.getAbsolutePath()); System.out.println(son.getParent()); }
输出:
/joey/soft/son.txt
/joey/soft
第四种
@Test public void test4() throws Exception{ File f = new File("/joey/soft","son.txt"); File son = new File(f.toURI()); System.out.println(son.getAbsolutePath()); System.out.println(son.getParent()); }
输出
/joey/soft/son.txt
/joey/soft
当然也可以不写绝对路径,写相对路径。
@Test public void test5() throws Exception{ File son = new File("test.txt"); System.out.println(son.getAbsolutePath()); System.out.println(son.getParent()); }
输出
/home/joey/eclipse/workspace/IOTest/test.txt
null
参考:http://docs.oracle.com/javase/7/docs/api/java/io/File.html#File(java.net.URI)
标签:
原文地址:http://www.cnblogs.com/Iqiaoxun/p/5966624.html