gpt4 book ai didi

java - 如果我希望它通过命令行将项目作为 jar 文件运行,某些属性文件的路径应该是什么样子

转载 作者:太空宇宙 更新时间:2023-11-04 07:37:08 25 4
gpt4 key购买 nike

我有一个依赖 jar 文件的简单项目。 Jar 文件有一个带有构造函数的类,该构造函数接受 props.xml 的路径。

这是项目结构:

这是主类:enter image description here

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)

最佳答案

由于您只为 File 类提供了一个文件名(间接通过构造函数),因此它假定您的意思是它是相对路径(相对于当前目录)。换句话说,它相当于 .\props.xml,并且由于命令行上的当前目录是 C:\Users\javaMan\(当您执行 Java -jar DummyFilePath.jar 时,您可以在命令提示符左侧看到该目录),因此它会在那里查找。您可能需要指定 props.xml 的绝对文件路径。

例如,如果 props.xml 位于 C:\Users\javaMan\someotherfolder 中,则绝对路径(至少在 Windows 中)将为 C:\Users\javaMan\someotherfolder\props.xml

关于java - 如果我希望它通过命令行将项目作为 jar 文件运行,某些属性文件的路径应该是什么样子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16679746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com