1

我有一个简单的项目,它依赖于 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)
4

2 回答 2

1

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

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

于 2013-05-21T21:30:32.307 回答
0

导出 this 时,不要忘记添加资源。它们并不总是被添加,一些构建器会过滤资源。

于 2013-05-21T21:44:58.653 回答