ByteArrayOutputStream到String Array

时间:2014-05-29 06:35:58

标签: java string bytearrayoutputstream

我正在编写一个应用程序,它有一个从我的服务器下载文本文件的方法。该文本文件将包含~1,000个代理IP。下载将每10分钟发生一次。我需要找到最有效的方法。

目前我在一个名为Connection的类中有一个方法,它将返回我想要检索的任何字节。因此,如果我使用这种方法连接到服务器的文本文件,我将以字节为单位返回它。我的另一种方法是从这些字节创建一个非常长的字符串。之后,我使用System.LineSeparator将长字符串拆分为数组。这是代码:

 public static void fetchProxies(String url) {
    Connection c = new Connection();
    List<Proxy> tempProxy = new ArrayList<Proxy>();
    ByteArrayOutputStream baos = 
            c.requestBytes(url);  
    String line = new String(baos.toByteArray()); 

    String[] split = line.split(System.lineSeparator());
    //more code to come but the above works fine.

}

这目前有效,但我知道这不是最有效的方法。我

我的问题
不是将字节转换为非常长的字符串,而是将字节转换为IP的最有效方法是什么,这样我就可以将每个单独的IP添加到arraylist中,然后返回充满IP的arraylist?

2 个答案:

答案 0 :(得分:2)

最有效和最合理的方法是创建BufferedReader包裹InputStreamReader包裹URL连接的InputStream。您可以在readLine()上使用BufferedReader,直到它返回null,并将每行读取附加到IP地址列表中:

List<String> ipList = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), theAppropriateEncoding))) {
    String line;
    while ((line = reader.readLine()) != null) {
        ipList.add(line);
    }
}

请注意,这可能不会在方法的性能上发生太大变化,因为大部分时间都花在等待来自远程主机的fof字节上,这比构建和分割内存中的字符串。

答案 1 :(得分:0)

String中的split方法并不是分离所有IP的最快方法。还有其他库可以更优化的方式实现这一目标。 阅读:http://demeranville.com/battle-of-the-tokenizers-delimited-text-parser-performance/

对于分割字符串的7种不同方法,有一个非常好的时间比较。

例如,Guava库中的Splitter类返回一个Iterable,而使用Guava,您还可以将结果转换为List:

import com.google.common.base.Splitter;
...
public static void fetchProxies(String url) {
Connection c = new Connection();
List<Proxy> tempProxy = new ArrayList<Proxy>();
ByteArrayOutputStream baos = 
        c.requestBytes(url);  
String line = new String(baos.toByteArray()); 

Iterator<Element> myIterator = 
    Splitter.on(System.getProperty("line.separator")).split(line);
List<Element> myList = Lists.newArrayList(myIterator);

// do somethjing with the List...