使用getResource()和txt文件(Java)的问题 [英] Issues using getResource() with txt file (Java)

查看:140
本文介绍了使用getResource()和txt文件(Java)的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在我的程序中使用txt文件(包括读和写)的设置。目前,我已经安装了我的机器上的本地文件路径,但是我需要把它打包成一个可执行的JAR文件。要做到这一点,我已经尝试将文件路径字符串切换到以下:

  String filepath = MyClass.class.getResource( /resources/textfile.txt); 

然而,当我运行这个时,我得到了一堆错误。谷歌搜索后,我发现了类似的方法 getResourceAsStream ,我也试过。这似乎返回一个InputStream对象,但是我需要理想的文件路径作为一个字符串。这可能吗?如果不是我的选择是什么?



附加信息

这里是尝试阅读时收到的错误消息&写入到txt文件中:

  java.io.FileNotFoundException:/ Users / Fred / Documents / Eclipse%20Projects / RandomProject / bin /resources/textfile.txt(没有这样的文件或目录)


解决方案

<那么你所提供的代码将不会被编译,因为 Class.getResource 返回一个 URL ,而不是字符串。你不能把资源当作只是另一个文件,因为它不是。

你应该根据需要改变读取文件接受一个 InputStream 而不是文件名,然后传入调用结果 getResourceAsStream()


I have a setup in which I make use of a txt file (both reading and writing to it) in my program. At present I have it setup such that I use the local filepath on my machine, however I need to package it up into an executable JAR. To do this I've tried switching the filepath string over to the following:

String filepath = MyClass.class.getResource("/resources/textfile.txt");

However, when I run this I get a bunch of errors. After googling the method I found the similar method getResourceAsStream which I have also tried. This seems to return an InputStream object, however I need the filepath as a string ideally. Is this possible? If not what are my options?

Additional Info:

Here are the error messages I receive when trying to read & write to the txt file:

java.io.FileNotFoundException:/Users/Fred/Documents/Eclipse%20Projects/RandomProject/bin/resources/textfile.txt (No such file or directory)

解决方案

Well the code you've given won't compile, because Class.getResource returns a URL, not a String. You can't treat the resource as "just another file" - because it's not.

You should basically change whatever needs to read the file to accept an InputStream instead of a filename, and then pass in the result of calling getResourceAsStream().

这篇关于使用getResource()和txt文件(Java)的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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