有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java spring工具套件创建runnable jar错误查找配置文件

我第一次尝试在spring工具套件中创建一个可运行的jar。我使用了导出功能并创建了jar文件,但在运行它时,出现了以下错误:

java.io.FileNotFoundException: config.properties (The system cannot find 
the file specified)

我在这里找到了一些建议的解决方案,将文件放在源文件夹中,即使我这样做了,它仍然看不到文件。我甚至把它放在了多个地方,希望能奏效

enter image description here

在这里,我打电话给全班同学阅读文件:

public static void main(String[] args) {
    // TODO Auto-generated method stub
      System.out.println("GETTING CONFIG PROPERTIES FILE...");
      configuration.readConfig();

....
public static void readConfig() {

    Properties fileProp = new Properties();
    try {

        //OutputStream output = null;
        URL url1 = configuration.class.
                getClassLoader().getResource("config.properties");
        File f = new File(url1.getFile());
        FileReader rd = new FileReader(f.getPath());

        //InputStream infile = new FileInputStream("config.properties");
        fileProp.load(rd); 

编辑:

通过插入斜杠更改了文件名路径,但似乎无法找到文件:

LOADING CONFIG PROPERTIES FILE...
 Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.jdt.internal.jarinjarloader.
    JarRsrcLoader.main(JarRsrcLoader.java:58)
    Caused by: java.lang.NullPointerException
    at com.ccccc.hbasededuper.
    configuration.readConfig(configuration.java:48)
    at com.ccccc.hbasededuper.HBaseMain.main(HBaseMain.java:144)
    ... 5 more

这行代码恰好是这样的:

       URL url1 = configuration.class.getClassLoader().
       getResource("/config.properties");

        System.out.println("LOADING CONFIG PROPERTIES FILE...");

        File f = new File(url1.getFile());
        FileReader rd = new FileReader(f.getPath());

错误以url1的形式出现。获取文件

编辑2:

弄明白了;问题是我读取属性文件的方式

fileprop.load(ClassLoader.getSystemResourceAsStream("config.properties"))

共 (1) 个答案

  1. # 1 楼答案

    我很确定你想要的是src/main/resources中的那个,可以通过

    configuration.class.getClassLoader().getResources("/config.properties")
    

    注意“/”