簡體   English   中英

Java NIO文件系統

[英]Java NIO filesystem

我正在嘗試創建一個Java Swing應用程序,其中將一些圖像文件和CSV文件存儲在子目錄中

   com/p/d/resources/project/MyProject

在上面的項目中,還有其他子目錄將存儲圖像和CSV文件。 如何無縫訪問以上目錄。 即使我將這個項目作為一個JAR(最終將要執行)或在Eclipse上運行,它也應該允許我以java.nio.file.Path或java.io.File的身份訪問上述目錄。
我知道我可以創建一個用於迭代JAR的文件系統,但是當我在Eclipse中將其作為應用程序運行時,相同的代碼不起作用。 以下是我用於JAR文件方案的代碼:

      String projectLocationPath = ApplicationProperties
                .get(PhaserDesktopConstants.PROJECT_LOCATION_PATH);
        CodeSource src = MainController.class.getProtectionDomain()
                .getCodeSource();
        if (src != null) {
            URL jar = src.getLocation();
            FileSystem fs = FileSystems.newFileSystem(jar.toURI().normalize(), null);
            Path projectDirectory = fs.getPath(projectLocationPath);
            if (!Files.isDirectory(projectDirectory)) {
                return null;
            }
          }

其中PhaserDesktopConstants.PROJECT_LOCATION_PATH代表我在上面給出的路徑。 我想在具有JAR和不具有JAR的兩種情況下都運行以上代碼。 我走的路

    file:/D:/shailesh/technical/work/eclipse_ws/Phaser%20Desktop/bin/

當我在Eclipse中運行並調用

    FileSystems.newFileSystem(..)

這給了我例外

     java.lang.IllegalArgumentException: Path component should be '/'

在SO上的一些帖子之后,我嘗試了硬編碼並從

     file:/D:/shailesh/technical/work/eclipse_ws/Phaser%20Desktop/bin/

  file:///D:/shailesh/technical/work/eclipse_ws/Phaser%20Desktop/bin/
  file://D:/shailesh/technical/work/eclipse_ws/Phaser%20Desktop/bin/
  file:///shailesh/technical/work/eclipse_ws/Phaser%20Desktop/bin/  
  file://shailesh/technical/work/eclipse_ws/Phaser%20Desktop/bin/

但沒有一個成功。

只是更新:當我在Eclipse中調試我的JAR時,它為我提供了以下路徑作為CodeSource的位置:

 file:/D:/shailesh/technical/PhaserD.jar

但是錯誤是相同的,它無法創建文件系統。 我的操作系統是Windows7。JDK 7

您可以替換. 使用./../切換到父目錄或您想要的任何引用路徑。 p保存絕對路徑,您可以刪除toAbsolutePath()以獲得referencePath

Path p = FileSystems.getDefault().getPath(".").toAbsolutePath();
System.out.println(p);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM