Java NIO file path issue

前端 未结 8 1969
臣服心动
臣服心动 2020-12-01 11:36

I used the following code to get the path

Path errorFilePath = FileSystems.getDefault().getPath(errorFile);

When I try to move

相关标签:
8条回答
  • 2020-12-01 12:11

    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.

    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    String platformIndependentPath = Paths.get(classloader.getResource(errorFile).toURI()).toString();
    
    0 讨论(0)
  • 2020-12-01 12:22

    To be sure to get the right path on Windows or Linux on any drive letter, you could do something like this:

    path = path.replaceFirst("^/(.:/)", "$1");
    

    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.

    0 讨论(0)
  • 2020-12-01 12:22

    Normal Windows Environment

    Disclaimer: I haven't tested this on a normal windows environment.

    "\\C:\\" needs to be "C:\\"

    final Path errorFilePath = Paths.get(FileSystems.getDefault().getPath(errorFile).toString().replace("\\C:\\","C:\\"));
    

    Linux-Like Windows Environment

    My Windows box has a Linux-Like environment so I had to change "/C:/" to be "C:\\".

    This code was tested to work on a Linux-Like Windows Environment:

    final Path errorFilePath = Paths.get(FileSystems.getDefault().getPath(errorFile).toString().replace("/C:/","C:\\"));
    
    0 讨论(0)
  • 2020-12-01 12:25

    The path \C:\Sample\sample.txt must not have a leading \. It should be just C:\Sample\sample.txt

    0 讨论(0)
  • 2020-12-01 12:29

    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()
    
    0 讨论(0)
  • 2020-12-01 12:29

    try to use like this 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.

    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

    and it will find the same file on Windows. However, we still have the "root" of the path as a problem.

    The easiest solution to deal with files on multiple platforms is to always use relative path names. A file name like Sample/sample.txt

    0 讨论(0)
提交回复
热议问题