Java 使用classpath:resources/jdbc.properties加载属性文件
如果从命令行执行下面的命令,如何使用核心java加载属性文件-Java 使用classpath:resources/jdbc.properties加载属性文件,java,maven,url,classpath,Java,Maven,Url,Classpath,如果从命令行执行下面的命令,如何使用核心java加载属性文件- mvn clean package exec:java -Dexec.mainClass="com.crossover.trial.properties.Main" -Dexec.args="classpath:resources/jdbc.properties" 在我使用的类文件中 Properties prop1 = new Properties(); URL url1 = ClassLoader.g
mvn clean package exec:java -Dexec.mainClass="com.crossover.trial.properties.Main" -Dexec.args="classpath:resources/jdbc.properties"
在我使用的类文件中
Properties prop1 = new Properties();
URL url1 = ClassLoader.getSystemResource("classpath:resources/jdbc.properties");
try{
prop1.load(url1.openStream());
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("------- By Using URL class -------");
System.out.println(prop1);
它给出空指针
请建议执行:java“-Dexec.args=param1 param2 param3”
因此,在您的示例中,exec:java“-Dexec.args=classpath:resources/jdbc.properties”
(查看“”位置),您将在args[0]处获得classpath:resources/jdbc.properties。您不需要在命令行上提供任何位置。或者以“classpath:”开头的资源名称。正如您在回答我之前的评论时所说的,对于src/main/resources下的属性文件,maven jar插件将把它放在类路径上的jar中 此代码:
package com.crossover.trial.properties;
import java.net.URL;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
Properties prop1 = new Properties();
URL url1 = ClassLoader.getSystemResource("jdbc.properties");
try{
prop1.load(url1.openStream());
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("------- By Using URL class -------");
System.out.println(prop1);
}
}
好的
您似乎没有在清单中指定mainclass。要简化命令行,请使用maven jar插件添加它
您还可以使用maven antrun插件来启动它(因为我在Eclipse下工作,所以我避免使用exec maven插件,但除此之外,这只是一个品味问题):
或直接主类,无包装:
mvn clean compile antrun:run -Pclass-launcher
mvn clean compile exec:exec -Pclass-exec
就这样
更新
要使用exec maven插件,请添加到pom:
<profile>
<id>jar-exec</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${maven.exec.plugin.version}</version>
<configuration>
<executable>java</executable>
<arguments>
<argument>-jar</argument>
<argument>${project.build.directory}/${project.build.finalName}.jar</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>class-exec</id>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${maven.exec.plugin.version}</version>
<configuration>
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
<classpath />
<argument>${main.class}</argument>
</arguments>
</configuration>
</plugin>
</plugins>
</build>
</profile>
或直接主类,无包装:
mvn clean compile antrun:run -Pclass-launcher
mvn clean compile exec:exec -Pclass-exec
你有没有试过不用“classpath:”前缀?没有,我只想用classpath uri。这就是“resources/jdbc.properties”的要求。你的意思是“src/main/resources/jdbc.properties”?@atao-是的。但是应该与classpath:uri一起使用
mvn clean compile exec:exec -Pclass-exec