如何使用Java直接从Internet读取文本文件?
我正在尝试从在线文本文件中读取一些单词。
我尝试做这样的事情,
File file = new File("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner scan = new Scanner(file);
但它不起作用,我得到的
http://www.puzzlers.org/pub/wordlists/pocket.txt
是输出,我只想得到所有的单词。
我知道他们当时教过我这一点,但我现在不记得具体该怎么做了,非常感谢任何帮助。
I am trying to read some words from an online text file.
I tried doing something like this
File file = new File("http://www.puzzlers.org/pub/wordlists/pocket.txt");
Scanner scan = new Scanner(file);
but it didn't work, I am getting
http://www.puzzlers.org/pub/wordlists/pocket.txt
as the output and I just want to get all the words.
I know they taught me this back in the day but I don't remember exactly how to do it now, any help is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
对于本地计算机以外的任何访问,请使用
URL
而不是File
。实际上,URL 甚至更普遍有用,还可以用于本地访问(使用
file:
URL)、jar 文件以及可以以某种方式检索的所有内容。上述方式以您的平台默认编码解释文件。如果您想使用服务器指示的编码,则必须使用 URLConnection 并解析其内容类型,如 这个问题。
关于您的错误,请确保您的文件编译时没有任何错误 - 您需要处理异常。单击 IDE 给出的红色消息,它应该向您显示如何修复它的建议。不要启动无法编译的程序(即使 IDE 允许这样做)。
这里有一些异常处理示例:
Use an
URL
instead ofFile
for any access that is not on your local computer.Actually, URL is even more generally useful, also for local access (use a
file:
URL), jar files, and about everything that one can retrieve somehow.The way above interprets the file in your platforms default encoding. If you want to use the encoding indicated by the server instead, you have to use a URLConnection and parse it's content type, like indicated in the answers to this question.
About your Error, make sure your file compiles without any errors - you need to handle the exceptions. Click the red messages given by your IDE, it should show you a recommendation how to fix it. Do not start a program which does not compile (even if the IDE allows this).
Here with some sample exception-handling:
尝试这样的事情
然后将其用作任何普通的旧输入流
try something like this
Then use it as any plain old input stream
对我真正有用的:(来源:oracle 文档“阅读 url”)
What really worked to me: (source: oracle documentation "reading url")
使用
Apache Commons IO
:Using
Apache Commons IO
:使用此代码将 Internet 资源读入
String
:这基于 这里。
Use this code to read an Internet resource into a
String
:This is based on here.
对于老式输入流,请使用以下代码:
For an old school input stream, use this code:
我按照以下方式对图像执行了此操作,您应该能够使用类似的步骤对文本执行此操作。
I did that in the following way for an image, you should be able to do it for text using similar steps.
或者,您可以使用 Guava 的资源 对象:
Alternatively, you can use Guava's Resources object:
更正的方法现已弃用。它给出了选择
私有 WeakReference活动参考;
这里的解决方案很有用 。
corrected method is deprecated now. It is giving the option
private WeakReference<MyActivity> activityReference;
here solution will useful.