如何在Java 7 java.nio.file.Path中访问子文件/文件夹? [英] How to access a sub-file/folder in Java 7 java.nio.file.Path?

查看:76
本文介绍了如何在Java 7 java.nio.file.Path中访问子文件/文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 7引入了 java.nio.file .Path 作为java.io.File的可能替代。 / p>

使用文件,当我访问特定的文件时,我会这样做:

 文件parent = new File(c:\\ tmp); 
File child = new File(parent,child); //这次访问c:\ tmp \child

使用Path执行此操作的方法是什么?



我认为这样可行:

  Path parent = Paths。获得( C:\\tmp); 
Path child = Paths.get(parent.toString(),child);

但是调用 parent.toString()似乎丑陋。有更好的方法吗?

解决方案

使用 resolve < 上的/ a>方法路径



此名称有两种方法。 一个需要一个相对路径另一个 字符串。它使用 Path 作为父对象,并附加 String 或相对路径相应。

 路径父= Paths.get(c:\\ tmp ); 
Path child = parent.resolve(child);


Java 7 introduced java.nio.file.Path as a possible replacement for java.io.File.

With File, when I access a file under a specific, I would do:

File parent = new File("c:\\tmp");
File child = new File(parent, "child"); // this accesses c:\tmp\child

What's the way to do this with Path?

I supposed this will work:

Path parent = Paths.get("c:\\tmp");
Path child = Paths.get(parent.toString(), "child");

But calling parent.toString() seems ugly. Is there a better way?

解决方案

Use the resolve method on Path.

There are two methods with this name. One takes a relative Path and the other a String. It uses the Path on which it is called as a parent and appends the String or relative Path appropriately.

Path parent = Paths.get("c:\\tmp");
Path child = parent.resolve("child");

这篇关于如何在Java 7 java.nio.file.Path中访问子文件/文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆