创建NIO入口Path(NIO 一)

Java SE 7发行版中引入的Path类是java.nio.file·包的主要入口点之一,下面将列出了在NIO中创建Path的6种方法。

定义绝对Path

让我们看下面的代码示例。

public class PathTest {
	public static void main(String[] args) {
		Path absolutePath = Paths.get("C:/temp/a/b/sample.txt");
		Path absolutePath1 = Paths.get("C:/temp/a/b", "sample.txt");
		Path absolutePath2 = Paths.get("C:/temp", "a/b", "sample.txt");
		Path absolutePath3 = Paths.get("C:/temp", "a", "b", "sample.txt");

		System.out.println(absolutePath);
		System.out.println(absolutePath1);
		System.out.println(absolutePath2);
		System.out.println(absolutePath3);
	}
}

运行结果

C:\temp\a\b\sample.txt
C:\temp\a\b\sample.txt
C:\temp\a\b\sample.txt
C:\temp\a\b\sample.txt

定义相对于根目录的Path

使用字符/开头(windows也可以使用c:/),让我们看下面的代码示例。这里使用/

public class PathTest2 {
	public static void main(String[] args) {
		Path relativePath1 = Paths.get("/temp/a/b/sample.txt");
		System.out.println(relativePath1.toAbsolutePath());
	}
}

运行结果

C:\temp\a\b\sample.txt

定义相对于当前工作目录的Path

让我们看下面的代码示例。

public class PathTest3 {
	public static void main(String[] args) {
		Path relativePath1 = Paths.get("config", "test.properties");
		System.out.println(relativePath1.toAbsolutePath());
	}
}

运行结果

C:\temp-workspace\workspace\daytest\config\test.properties

定义URI方法的Path

让我们看下面的代码示例。

public class PathTest4 {
	public static void main(String[] args) {
		URI uri = URI.create("file:///temp/a/b/sample.txts");
		String scheme =  uri.getScheme();
		
		// scheme类型为:file
		if (scheme.equalsIgnoreCase("file")) {
		    System.out.println(Paths.get(uri).toAbsolutePath());
		}
		 
		// 不知道scheme类型为:file
		for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {
		    if (provider.getScheme().equalsIgnoreCase(scheme)) {
		        System.out.println(provider.getPath(uri).toAbsolutePath());
		        break;
		    }
		}
	}
}

运行结果

C:\temp\a\b\sample.txts
C:\temp\a\b\sample.txts

使用File Systems定义获取Path

让我们看下面的代码示例。

public class PathTest5 {
	public static void main(String[] args) {
		Path relativePath1 = FileSystems.getDefault().getPath("/temp/a/b/sample.txts");
		System.out.println(relativePath1.toAbsolutePath());
	}
}

运行结果

C:\temp\a\b\sample.txts
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值