Java NIO file path issue

前端 未结 8 1973
臣服心动
臣服心动 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:34

    To make it work on both Windows and Linux\OS X consider doing this:

    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

    private static final boolean IS_WINDOWS = System.getProperty( "os.name" ).contains( "indow" );
    

    and then use:

    String osAppropriatePath = IS_WINDOWS ? filePath.substring(1) : filePath;
    
    0 讨论(0)
  • 2020-12-01 12:35

    Depending on how are you going to use the Path object, you may be able to avoid using Path at all:

    // 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);
    
    0 讨论(0)
提交回复
热议问题