【发布时间】:2017-09-26 14:56:47
【问题描述】:
我在 Eclipse 中有一个简单的 maven 项目。该应用程序包含文件:src/main/resources/test.txt。我想读取文件并将其写入输出。它在 Eclipse 中工作,但在创建 jar 文件后不能从命令行工作。如何配置项目以两种方式工作。 我哪里错了? jar 文件、java 代码、manifest、maven 配置不正确?
应用结构:
跑步:
java -jar fileRead-0.0.1-SNAPSHOT.jar
错误:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/io/IOUtils
at fileRead.FileRead.main(FileRead.java:11)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.io.IOUtils
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
Java 代码:
package fileRead;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
public class FileRead {
public static void main(String[] args) {
String file = null;
try {
file = IOUtils.toString((new FileRead()).getClass().getClassLoader().getResourceAsStream("test.txt"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(file);
}
}
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fileRead</groupId>
<artifactId>fileRead</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>fileRead</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>fileRead.FileRead</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
fileRead-0.0.1-SNAPSHOT.jar:
fileRead
FileRead.class
META-INF
maven
MANIFEST.MF
test.txt
清单.MF:
Manifest-Version: 1.0
Built-By: msmorenda
Class-Path: org.apache.commons.io-2.4.jar commons-io-2.4.jar
Created-By: Apache Maven 3.5.0
Build-Jdk: 1.8.0_121
Main-Class: fileRead.FileRead
test.txt:
abc
def
ghi
【问题讨论】:
-
你为什么要编译jar而不是java类?我认为maven有一个特定的结构,当你创建jar文件时没有名为“resources”或“main/java”的目录所以我没有找到它
-
当你说“它在 Eclipse 中工作,但在创建 jar 文件后不能从命令行工作” - 你的意思是它在 Eclipse 中工作,但不是当你在服务器上运行 JAR 文件时, Tomcat 之类的?
-
我没有服务器,只有 Windows 上的命令行。
-
你明白
java.lang.NoClassDefFoundError是什么意思吗?