简体   繁体   English

JAVA 从网络服务器读取文件和多个字符串

[英]JAVA Read file from webserver and multiple strings

So on our webserver we have an txt that has multiple lines.所以在我们的网络服务器上,我们有一个包含多行的 txt。 Each line has his own UUID (String) and we need to read that out in JAVA.每行都有自己的 UUID(字符串),我们需要在 JAVA 中读出它。

But every attempt results in just 1 line that is read so 1 string.但是每次尝试都会导致只有 1 行被读取,所以 1 个字符串。 How can we properly read multiple lines from a txt file of a webserver?我们如何正确地从网络服务器的 txt 文件中读取多行?

This is our code.这是我们的代码。

    static URL url;

static {
    try {
        url = new URL("https://example.com/test.txt");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

static String text;

static {
    try {
        text = new Scanner( url.openStream() ).useDelimiter(",").next();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Reading Directly from a URL直接从 URL 读取

After you've successfully created a URL, you can call the URL's openStream() method to get a stream from which you can read the contents of the URL.成功创建 URL 后,可以调用 URL 的 openStream() 方法获取 stream,从中可以读取 ZE6B391A8D2C4D45902A23A8B658 的内容。 The openStream() method returns a java.io.InputStream object, so reading from a URL is as easy as reading from an input stream. The openStream() method returns a java.io.InputStream object, so reading from a URL is as easy as reading from an input stream.

import java.net.*;
import java.io.*;

public class URLReader {

public static void main(String[] args) throws Exception {

    URL oracle = new URL("http://www.url.com/file.txt");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(oracle.openStream()));

    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM