Java代码在Netbeans IDE中构建和清理后找不到资源文件? [英] Java code cannot find resource file after build and clean in Netbeans IDE?

查看:422
本文介绍了Java代码在Netbeans IDE中构建和清理后找不到资源文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的需要你的帮助来解决我自己的问题。现在,我正在处理小代码应用程序。在该项目文件夹中包含一些资源文件(* .xlsx,* .png,...)。我把它们放在当前文件夹中的代码文件。我只是想知道,当我在netbean ide中运行我的代码时,它只是找到了。



在构建代码项目后,我在dist目录中得到一个jar文件。我运行它。由于应用程序使用JFrame作为用户界面,所以它正常打开。但是,当我执行该应用程序的某些功能时,它显示了错误日志。这里是错误信息:

pre $ java.io.FileNotFoundException:
src\sample.xlsx(系统不能找到指定的路径)

有什么问题吗?

以下是我的一些代码:

$ $ $ $ $ $ copyFile(new File(src \\sample。 xlsx),
new File(txtout.getText()+\\sample.xlsx));

节点: copyFile函数用于从源文件复制到目标文件。



这是我在Netbean IDE中的项目文件夹结构:
$ b $ ol

  • 项目名称

    • 源代码包(src)

      • myClass.java,sample.xlsx等



      • 解决方案

        永远不要直接引用 src ,程序一旦建立,目录就不存在。其次,您不能通过 File 引用来访问嵌入在应用程序上下文中的资源,它们在文件系统上不再存在。



        相反,您需要使用 Class#getResource Class#getResourceAsStream

          URL url = getClass()。getResource(/ sample.xlsx); 
        InputStream is = getClass()。getResourceAsStream(/ sample.xlsx);
        //不要忘记适当地管理你的流...


        I really need your help to solve my own problem. Now, I'm dealing with small code app. In that project folder contain some resource files (*.xlsx, *.png,...). I placed them in current folder with code file. I just wonder that when I run my code in netbean ide, it just worked find.

        After I build code project, I get a jar file in "dist" directory. I run it. It open normally since app used JFrame as user interface. However, when I execute some function of that app, it showed me the error log. Here is the error message:

        java.io.FileNotFoundException: 
        src\sample.xlsx (The system cannot find the path specified)
        

        What's the matter out there?

        Here is some pieces of my code:

        copyFile(new File("src\\sample.xlsx"),
        new File(txtout.getText()+"\\sample.xlsx"));
        

        Node: copyFile function is used for copy file from source to dest.

        Here is my project folder structure in Netbean IDE:

        1. Project Name
          • Source Pakage(src)
            • myClass.java, sample.xlsx, etc

        解决方案

        First, never reference src directly, the directory will not exist once the program is built. Second, you can not access resources which have been embedded within in the application context via a File reference, they simply no longer exist on the file system.

        Instead, you need to use Class#getResource or Class#getResourceAsStream

        URL url = getClass().getResource("/sample.xlsx");
        InputStream is = getClass().getResourceAsStream("/sample.xlsx");
        // Don't forget to manage your streams appropriately...
        

        这篇关于Java代码在Netbeans IDE中构建和清理后找不到资源文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆