【问题标题】:Loading xml from .jar从 .jar 加载 xml
【发布时间】:2017-01-23 16:26:47
【问题描述】:

我正在尝试从 .jar(由 ant builder.xml 制作)加载 .xml 文件,但出现异常。

来自我的 ant build.xml 的代码:

我班的代码:

try {
xml = new File(this.getClass().getResource("/TaskData.xml").getFile());
    } catch (Exception e) {
        e.printStackTrace();

我得到的异常:

java.io.FileNotFoundException: C:\Users\agent_000\Desktop\....file:\C:\Users\agent_000\Desktop\%d1%85%d1%83\build\sample.jar!\TaskData.xml (

为什么找不到 .xml 文件?

提前致谢!

【问题讨论】:

  • 文件真的在jar里吗? (用winrar或其他打开它)
  • @flkes 根据 mybuild.xml(它是 ant 文件)正在创建一个 sample.jar,是的,这个 .jar 中的 TaskData.xml。
  • @flkes 不,同样的例外。 build.xml 可能有问题吗?
  • 不要将您的 XML 发布为图像。将实际文本复制到您的问题中。
  • URL 的 getFile() 方法将 URL 转换为文件,并且返回有效的文件名。使用new File(url.toURI()) 将 URL 转换为文件。

标签: java xml ant jar


【解决方案1】:

你可以这样做

    URL url = new URL("jar:file:/path--to-your Jar !/TaskData.xml");
    InputStream is = url.openStream();
    System.out.println(is);

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    System.out.println(reader.readLine());

或者通过 getResourceAsStream 让 ClassLoader 返回资源的 InputStream:

InputStream in = getClass().getResourceAsStream("/TaskData.txt"); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

【讨论】:

  • 感谢您的回答!但我需要创建一个“文件”类,所以我的类可以解析它
  • 你可以试试,File tempFile = File.createTempFile(prefix, suffix); tempFile.deleteOnExit(); FileOutputStream out = new FileOutputStream(tempFile); IOUtils.copy(in, out);返回临时文件;
猜你喜欢
  • 2011-05-06
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 2014-12-26
  • 2021-06-14
  • 2010-10-20
  • 2011-02-06
  • 2013-12-31
相关资源
最近更新 更多