我有一個簡單的項目,它依賴於jar文件。 Jar文件具有帶構造函數的單個類,其中包含props.xml的路徑。如果我希望它通過命令行將項目作爲jar文件運行,某些屬性文件的路徑應該如何顯示
這是項目結構:
這裏是主類:
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文件。當我在蝕運行我看到下面的輸出:
[#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)
從命令行運行時,您處於哪個目錄?當你打開一個沒有完整路徑的文件時,它將使用當前的工作目錄來查找它。 –
是jar中的屬性文件嗎? –
我複製了jar文件c:/ users/javaMan目錄 – javaMan