我有一个简单的项目,它依赖于 jar 文件。Jar 文件有一个带有构造函数的类,它接受 props.xml 的路径。
这是项目结构:
这是主要课程:
import com.file.reader.FileReader;
public class SimpleExample {
public static void main(String[]args){
FileReader rd = new FileReader("props.xml");
}
}
这是 FileReader.java
package com.file.reader;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class FileReader {
public FileReader(String fileName){
try {
File file = new File(fileName);
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = dBuilder.parse(file);
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
if (doc.hasChildNodes()) {
System.err.println((doc.getChildNodes()));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
这基本上是读取 xml 文件。
FileReader.java 是我的项目中正在访问的 jar 文件。当我在 Eclipse 中运行时,我看到以下输出:
[#document: null]
Root element :company
但是当我将 DummyFilePath 导出为 jar 文件并尝试从命令行运行时。
我看到正在抛出错误:
C:\Users\javaMan\props.xml (The system cannot find the file specified)
从命令行我正在运行
Java -jar DummyFilePath.jar
我怎样才能让它通过命令行运行
编辑
在检查了一些链接的问题后,我尝试了另一种方法:
我将 props.xml 移动到 src 文件夹。
然后我改变了 SimpleExample.java 如下:
import java.io.File;
import java.net.URL;
import com.file.reader.FileReader;
public class SimpleExample {
public static void main(String[] args) {
SimpleExample se = new SimpleExample();
System.err.println(se.getPath());
FileReader rd = new FileReader(se.getPath());
}
public String getPath(){
URL url1 = getClass().getClassLoader().getResource("props.xml");
File f = new File(url1.getFile());
return f.getAbsolutePath();
}
}
因此,当我在 Eclipse 中运行时,我看到以下内容很好:
C:\Users\javaMan\Perforce\DummyFilePath\bin\props.xml
[#document: null]
Root element :company
当我运行相同的 DummyFilePath.jar 时,我看到以下错误:
C:\Users\javaMan\Desktop>java -jar "C:\Users\javaMan\Desktop\DummyFilePath.jar"
C:\Users\javaMan\Desktop\file:\C:\Users\javaMan\Desktop\DummyFilePath.jar!\props.xml
C:\Users\javaMan\Desktop\file:\C:\Users\javaMan\Desktop\DummyFilePath.jar!\props.xml (The filename, directory name, or volume label syntax is incorrect)