我有两个文本文件,我想作为流抓取并转换为字符串.最终,我希望合并两个单独的文件.
到目前为止,我已经有了
//get the input stream of the files.
InputStream is =
cts.getClass().getResourceAsStream("/files/myfile.txt");
// convert the stream to string
System.out.println(cts.convertStreamToString(is));
Run Code Online (Sandbox Code Playgroud)
getResourceAsStream不会将多个字符串作为参数.那么我需要做什么?单独转换它们并合并在一起?
任何人都可以告诉我一个简单的方法吗?
听起来你想要连接流.您可以使用SequenceInputStream从多个流创建单个流.然后从该单个流中读取数据并根据需要使用它.
这是一个例子:
String encoding = "UTF-8"; /* You need to know the right character encoding. */
InputStream s1 = ..., s2 = ..., s3 = ...;
Enumeration<InputStream> streams =
Collections.enumeration(Arrays.asList(s1, s2, s3));
Reader r = new InputStreamReader(new SequenceInputStream(streams), encoding);
char[] buf = new char[2048];
StringBuilder str = new StringBuilder();
while (true) {
int n = r.read(buf);
if (n < 0)
break;
str.append(buf, 0, n);
}
r.close();
String contents = str.toString();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1887 次 |
| 最近记录: |