Java:导出到JAR后,Pathnames不工作 [英] Java: Pathnames not working once I export to JAR

查看:159
本文介绍了Java:导出到JAR后,Pathnames不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将项目导出到Eclipse中的可运行JAR。我的代码中有几个地方完成了以下操作。

  String file =src / Files / .. 。; 
loadFile(file); //纯粹例如

现在项目采用JAR的形式,似乎存在并加载这些文件失败。我很确定我引用的文件被包装在JAR中。当导出到JAR时,目录是否以任何特定的方式发生变化?任何有关如何使这项工作的其他想法?

解决方案

您需要将它们视为类路径资源,而不是本地磁盘文件系统路径。当您将文件打包在JAR中时,这不会起作用,也不希望依赖于工作目录。 JAR中的文件已经是类路径的一部分。



假设你有一个 foo.txt com.example ,那么你可以得到一个 InputStream ,如下

  InputStream input = getClass()。getResourceAsStream(/ com / example / foo.txt); 
// ...

或当您在 static context

  InputStream input = SomeClass.class.getResourceAsStream(/ com / example / foo。文本); 
// ...

或者当您要扫描全局类路径时

  InputStream input = Thread.currentThread()。getContextClassLoader()。getResourceAsStream(/ com / example / foo.txt); 
// ...



另请参见:




I have exported a project to a runnable JAR in eclipse. There are a few places in my code where I've done the following.

String file = "src/Files/...";
loadFile(file); // purely for example

Now that the project is in the form of a JAR, those directories don't seem to exist and loading those files fails. I'm pretty sure that the files I'm referencing are packed in the JAR. Do the directories change in any particular way when exported to JAR? Any other ideas on how to make this work?

解决方案

You need to treat them as a classpath resource, not as a local disk file system path. This isn't going to work when you package the files in a JAR and you also don't want to be dependent on the working directory. Files inside a JAR are part of the classpath already.

Assuming that you've a foo.txt file in package com.example, then you can get an InputStream of it as follows

InputStream input = getClass().getResourceAsStream("/com/example/foo.txt");
// ...

Or when you're inside static context

InputStream input = SomeClass.class.getResourceAsStream("/com/example/foo.txt");
// ...

Or when you want to scan the global classpath

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("/com/example/foo.txt");
// ...

See also:

这篇关于Java:导出到JAR后,Pathnames不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆