【问题标题】:File path working in NetBeans but not in built JAR file文件路径在 NetBeans 中有效,但在构建的 JAR 文件中无效
【发布时间】:2014-01-12 02:10:15
【问题描述】:

我正在尝试将文件从类路径复制到用户指定的位置。但是,在 netbeans 中运行程序时,文件路径正常工作并且文件被复制,但是当我构建一个 jar 文件并尝试相同时,它没有找到源文件。

URL url = getClass().getResource("utils/mount");
File file = new File(url.getPath());
this.copyEachFile(url.getPath(), "C:\\Users\\Nikhil\\Desktop\\" + mount); //this function takes in source path of file and copies it to destination path.

当我跟踪源路径时,我得到了

/C:/Users/Nikhil/Documents/NetBeansProjects/Aroma-Installer/build/classes/aroma/installer/utils/mount

在 netbeans 中并在 jar 中跟随

/C:/Users/Nikhil/Documents/NetBeansProjects/Aroma-Installer/dist/Aroma-Installer.jar!/aroma/installer/utils/mount

当我在 netbeans 中运行程序时,文件成功复制但在通过 jar 运行时,它说源不存在。 问题出在哪里?

【问题讨论】:

    标签: resources classloader


    【解决方案1】:

    好的,所以我创建了一个函数并按如下方式调用它。

    this.copyFileFromJar("utils/mount", "C:\\Users\\Nikhil\\Desktop\\mount");
    

    函数定义如下。

    public void copyFileFromJar(String source, String destination) throws IOException{
        File dest = new File(destination);
        if(!dest.exists()){
            dest.createNewFile();
    }
        InputStream in = null;
        OutputStream out = null;
        try{
            in = this.getClass().getResourceAsStream(source); //Important step, it returns InputStream which can be manipulated as per need.
            out = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int len;
            while((len = in.read(buf)) > 0){
                out.write(buf, 0, len);
        }
            JOptionPane.showMessageDialog(null, "File Successfully copied at" + dest.getAbsolutePath());
            System.out.println("File Writing......" + dest.getName());
        }
        finally{
            in.close();
            out.close();
        }
    }
    

    现在我可以将文件从 jar 文件复制到用户指定的位置。 希望这可以帮助任何正在寻找相同问题的人。

    【讨论】:

      猜你喜欢
      • 2020-05-17
      • 2018-10-18
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多