【问题标题】:How to read a text file directly from Internet using Java?如何使用 Java 直接从 Internet 读取文本文件?
【发布时间】:2011-09-09 16:50:37
【问题描述】:

我正在尝试从在线文本文件中读取一些单词。

我试着做这样的事情

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 

作为输出,我只想得到所有的单词。

我知道他们以前教过我这个,但我现在不记得具体该怎么做,非常感谢任何帮助。

【问题讨论】:

标签: java file text-files java.util.scanner


【解决方案1】:

使用Apache Commons IO

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public static String readURLToString(String url) throws IOException
{
    try (InputStream inputStream = new URL(url).openStream())
    {
        return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    }
}

【讨论】:

    【解决方案2】:

    我通过以下方式对图像执行此操作,您应该能够使用类似的步骤对文本执行此操作。

    // folder & name of image on PC          
    File fileObj = new File("C:\\Displayable\\imgcopy.jpg"); 
    
    Boolean testB = fileObj.createNewFile();
    
    System.out.println("Test this file eeeeeeeeeeeeeeeeeeee "+testB);
    
    // image on server
    URL url = new URL("http://localhost:8181/POPTEST2/imgone.jpg"); 
    InputStream webIS = url.openStream();
    
    FileOutputStream fo = new FileOutputStream(fileObj);
    int c = 0;
    do {
        c = webIS.read();
        System.out.println("==============> " + c);
        if (c !=-1) {
            fo.write((byte) c);
        }
    } while(c != -1);
    
    webIS.close();
    fo.close();
    

    【讨论】:

      【解决方案3】:

      或者,您可以使用Guava's Resources 对象:

      URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
      List<String> lines = Resources.readLines(url, Charsets.UTF_8);
      lines.forEach(System.out::println);
      

      【讨论】:

        【解决方案4】:

        使用此代码将 Internet 资源读入String

        public static String readToString(String targetURL) throws IOException
        {
            URL url = new URL(targetURL);
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(url.openStream()));
        
            StringBuilder stringBuilder = new StringBuilder();
        
            String inputLine;
            while ((inputLine = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(inputLine);
                stringBuilder.append(System.lineSeparator());
            }
        
            bufferedReader.close();
            return stringBuilder.toString().trim();
        }
        

        这是基于here

        【讨论】:

          【解决方案5】:

          真正对我有用的东西:(来源:oracle 文档“阅读 url”)

           import java.net.*;
           import java.io.*;
          
           public class UrlTextfile {
          public static void main(String[] args) throws Exception {
          
              URL oracle = new URL("http://yoursite.com/yourfile.txt");
              BufferedReader in = new BufferedReader(
              new InputStreamReader(oracle.openStream()));
          
              String inputLine;
              while ((inputLine = in.readLine()) != null)
                  System.out.println(inputLine);
              in.close();
          }
           }
          

          【讨论】:

            【解决方案6】:

            对于老式输入流,请使用以下代码:

              InputStream in = new URL("http://google.com/").openConnection().getInputStream();
            

            【讨论】:

            • 我收到一个错误:方法 URL(URL) 未定义为 Test 类型
            • 或将 openConnection().getInputStream() 替换为 openStream() ;)
            • 你需要“new”——我猜你是在“URL(...”)前面省略了“new”
            【解决方案7】:

            使用URL 而不是File 进行任何不在本地计算机上的访问。

            URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
            Scanner s = new Scanner(url.openStream());
            

            实际上,URL 更普遍有用,也可用于本地访问(使用file: URL)、jar 文件以及任何可以通过某种方式检索的内容。

            上述方式以您的平台默认编码解释文件。如果您想使用服务器指示的编码,则必须使用 URLConnection 并解析其内容类型,如this question 的答案中所示。


            关于您的错误,请确保您的文件编译时没有任何错误 - 您需要处理异常。单击 IDE 给出的红色消息,它应该向您显示如何修复它的建议。不要启动不能编译的程序(即使 IDE 允许这样做)。

            这里有一些异常处理示例:

            try {
               URL url = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
               Scanner s = new Scanner(url.openStream());
               // read from your scanner
            }
            catch(IOException ex) {
               // there was some connection problem, or the file did not exist on the server,
               // or your URL was not in the right format.
               // think about what to do now, and put it here.
               ex.printStackTrace(); // for now, simply output it.
            }
            

            【讨论】:

            • 我在线程“main”java.lang.Error 中遇到了一个错误:未解决的编译问题:未处理的异常类型 MalformedURLException 未处理的异常类型 IOException
            • 将其包装在 try/catch 块中并捕获这 2 个异常。
            • 对不起,我迷路了,这不应该很简单,可以用 2 或 3 行代码完成吗?
            • @theexplorer 参见en.wikipedia.org/wiki/HTTP_403,例如。您的服务器似乎配置为不允许下载此文件。
            • 我明白了。谢谢。要求主机关闭此安全开关是否明智?
            【解决方案8】:

            试试这样的

             URL u = new URL("http://www.puzzlers.org/pub/wordlists/pocket.txt");
             InputStream in = u.openStream();
            

            然后将其用作任何普通的旧输入流

            【讨论】:

              猜你喜欢
              • 2014-10-28
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-08-31
              • 2019-01-11
              • 1970-01-01
              相关资源
              最近更新 更多