如何从jar文件中读取文件? [英] How to read a file from a jar file?

查看:27
本文介绍了如何从jar文件中读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JAR 文件中有一个文件.例如,它是 1.txt.

I have a file in a JAR file. It's 1.txt, for example.

我如何访问它?我的源代码是:

How can I access it? My source code is:

Double result=0.0;
File file = new File("1.txt")); //how get this file from a jar file
BufferedReader input = new BufferedReader(new FileReader(file));
String line;
while ((line = input.readLine()) != null) {
  if(me==Integer.parseInt(line.split(":")[0])){
    result= parseDouble(line.split(":")[1]);
  }
}
input.close();
return result;

推荐答案

你不能使用 File,因为这个文件在文件系统中不是独立存在的.相反,您需要 getResourceAsStream(),如下所示:

You can't use File, since this file does not exist independently on the file system. Instead you need getResourceAsStream(), like so:

...
InputStream in = getClass().getResourceAsStream("/1.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(in));
...

这篇关于如何从jar文件中读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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