Java NIO 文件路径问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9834776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java NIO file path issue
提问by Kathir
I used the following code to get the path
我使用以下代码来获取路径
Path errorFilePath = FileSystems.getDefault().getPath(errorFile);
When I try to move a file using the File NIO, I get the error below:
当我尝试使用 File NIO 移动文件时,出现以下错误:
java.nio.file.InvalidPathException: Illegal char <:> at index 2: \C:\Sample\sample.txt
I also tried using URL.encode(errorFile)
which results in the same error.
我也尝试使用URL.encode(errorFile)
which 导致相同的错误。
采纳答案by Jim Garrison
The path \C:\Sample\sample.txt
must not have a leading \
. It should be just C:\Sample\sample.txt
路径\C:\Sample\sample.txt
不能有前导\
。应该只是C:\Sample\sample.txt
回答by Riddhish.Chaudhari
try to use like this C:\\Sample\\sample.txt
尝试像这样使用 C:\\Sample\\sample.txt
Note the double backslashes. Because the backslash is a Java String escape character, you must type two of them to represent a single, "real" backslash.
注意双反斜杠。由于反斜杠是 Java 字符串转义字符,因此您必须键入其中的两个以表示单个“真正的”反斜杠。
or
或者
Java allows either type of slash to be used on any platform, and translates it appropriately. This means that you could type. C:/Sample/sample.txt
Java 允许在任何平台上使用任一类型的斜杠,并对其进行适当的转换。这意味着您可以键入。C:/Sample/sample.txt
and it will find the same file on Windows. However, we still have the "root" of the path as a problem.
它会在 Windows 上找到相同的文件。但是,我们仍然将路径的“根”视为问题。
The easiest solution to deal with files on multiple platforms is to always use relative path names. A file name like Sample/sample.txt
处理多个平台上的文件的最简单解决方案是始终使用相对路径名。像这样的文件名Sample/sample.txt
回答by Korey Hinton
Normal Windows Environment
普通 Windows 环境
Disclaimer: I haven't tested this on a normal windows environment.
免责声明:我没有在普通的 Windows 环境中测试过这个。
"\\C:\\"
needs to be "C:\\"
"\\C:\\"
需要是 "C:\\"
final Path errorFilePath = Paths.get(FileSystems.getDefault().getPath(errorFile).toString().replace("\C:\","C:\"));
Linux-Like Windows Environment
类似 Linux 的 Windows 环境
My Windows box has a Linux-Like environment so I had to change "/C:/"
to be "C:\\"
.
我的 Windows 机器有一个类似 Linux 的环境,所以我不得不更改"/C:/"
为"C:\\"
.
This code was tested to work on a Linux-Like Windows Environment:
此代码经过测试可在类似 Linux 的 Windows 环境中工作:
final Path errorFilePath = Paths.get(FileSystems.getDefault().getPath(errorFile).toString().replace("/C:/","C:\"));
回答by Sled
To make it work on both Windows and Linux\OS X consider doing this:
要使其在 Windows 和 Linux\OS X 上都能运行,请考虑这样做:
String osAppropriatePath = System.getProperty( "os.name" ).contains( "indow" ) ? filePath.substring(1) : filePath;
If you want to worry about performance I'd store System.getProperty( "os.name" ).contains( "indow" )
as a constant like
如果您想担心性能,我会将其存储System.getProperty( "os.name" ).contains( "indow" )
为常量,例如
private static final boolean IS_WINDOWS = System.getProperty( "os.name" ).contains( "indow" );
and then use:
然后使用:
String osAppropriatePath = IS_WINDOWS ? filePath.substring(1) : filePath;
回答by Alexandr
You need to convert the found resource to URI. It works on all platforms and protects you from possible errors with paths. You must not worry about how full path looks like, whether it starts with '\' or other symbols. If you think about such details - you do something wrong.
您需要将找到的资源转换为URI。它适用于所有平台,并保护您免受路径可能出现的错误。您不必担心完整路径的外观,是否以“\”或其他符号开头。如果你考虑这些细节——你做错了。
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
String platformIndependentPath = Paths.get(classloader.getResource(errorFile).toURI()).toString();
回答by Eric
To be sure to get the right path on Windows or Linux on any drive letter, you could do something like this:
为了确保在 Windows 或 Linux 上的任何驱动器号上获得正确的路径,您可以执行以下操作:
path = path.replaceFirst("^/(.:/)", "");
That says: If the beginning of the string is a slash, then a character, then a colon and another slash, replace it with the character, the colon, and the slash (leaving the leading slash off).
也就是说:如果字符串的开头是一个斜杠,然后是一个字符,然后是一个冒号和另一个斜杠,用字符、冒号和斜杠替换它(去掉前导斜杠)。
If you're on Linux, you shouldn't end up with a colon in your path, and there won't be a match. If you are on Windows, this should work for any drive letter.
如果您使用的是 Linux,则路径中不应以冒号结尾,否则不会有匹配项。如果您使用的是 Windows,这应该适用于任何驱动器号。
回答by hueami
Another way to get rid of the leading separator is to create a new file and convert it to a string then:
摆脱前导分隔符的另一种方法是创建一个新文件并将其转换为字符串,然后:
new File(Platform.getInstallLocation().getURL().getFile()).toString()
回答by golimar
Depending on how are you going to use the Path object, you may be able to avoid using Path at all:
根据您将如何使用 Path 对象,您可能完全可以避免使用 Path:
// works with normal files but on a deployed JAR gives "java.nio.file.InvalidPathException: Illegal char <:> "
URL urlIcon = MyGui.class.getResource("myIcon.png");
Path pathIcon = new File(urlIcon.getPath()).toPath();
byte bytesIcon[] = Files.readAllBytes(pathIcon);
// works with normal files and with files inside JAR:
InputStream in = MyGui.class.getClassLoader().getResourceAsStream("myIcon.png");
byte bytesIcon[] = new byte[5000];
in.read(bytesIcon);