Java 读取URL的第一行文本

Java 读取URL的第一行文本,java,url,Java,Url,我正在尝试读取URL的第一行。 然后我想在以后的代码中将其用作字符串。 有人能帮我吗? 我已经试过了 public static String main(String[] args) { try { URL url = new URL("myurlhere"); // read text returned by server BufferedReader in = new BufferedReader(new InputStr

我正在尝试读取URL的第一行。 然后我想在以后的代码中将其用作字符串。 有人能帮我吗? 我已经试过了

    public static String main(String[] args) {

    try {

        URL url = new URL("myurlhere");

        // read text returned by server
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        String line;
        while ((line = in.readLine()) != null) {
            return line;
        }
        in.close();

    }
    catch (MalformedURLException e) {
        System.out.println("Malformed URL: " + e.getMessage());
    }
    catch (IOException e) {
        System.out.println("I/O Error: " + e.getMessage());
    }
    return null;

}

我就是无法从中提取字符串。

如果您想使用URL从internet上的文件中读取内容,则应使用URLConnection

下面是一个简单的例子:

    String string = "";
    try {
        URLConnection connection = new URL(
                "http://myurl.org/mypath/myfile")
                .openConnection();
        Scanner scanner = new Scanner(connection.getInputStream());
        while (scanner.hasNext()) {
            string += scanner.next() + " ";
        }
        scanner.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Do something with the string.
你可以考虑使用你的目的:

try {
        Document doc = Jsoup.connect("http://popofibo.com/pop/swaying-views-of-our-past/").get();
        Elements paragraphs = doc.select("p");
        for(Element p : paragraphs) {
          System.out.println(p.text());
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
输出:

对人类文明进化的主流观点进行争论确实很困难


嘿,莱纳斯,谢谢你的回复,但是msg应该是什么呢?@user3187533哦,对不起,我是想做
string+=scanner.next()+”。我现在就修。嘿,莱纳斯,谢谢!它起作用了,但它把“ï»放在了前面。你知道怎么去掉这个吗?编辑:无需担心。我用子字符串(3)修复了它,但如果您知道要读取的字符集,则始终可以添加一个参数,例如
Scanner Scanner=new Scanner(connection.getInputStream(),”
。是您可能要尝试的字符集列表。