Java从IOUtils的InputStrem(特别是copyBytes)动态写入字符串数组
在阅读了the documentation from ^{IOUtils
)之后,我们可以在这里看到它的参数:
copyBytes:
public static void copyBytes(InputStream in,
OutputStream out,
int buffSize,
boolean close) throws IOException
从一个流复制到另一个流
参数:
in - InputStrem to read from
out - OutputStream to write to
buffSize - the size of the buffer
close - whether or not close the InputStream and OutputStream at the end. The streams are closed in the finally clause.
投掷:
IOException
考虑到这些信息,我得到了如下数据结构:
List<String> inputLinesObject = IOUtils.readLines(in, "UTF-8");
^我希望这是一个可扩展的字符串数组列表,我可以用copyBytes
方法读取的文件中的数据填充它
然而,下面是我调用copyBytes
方法时使用的代码:
IOUtils.copyBytes(in, inputLinesObject, 4096, false);
你看到inputLinesObject
的地方,这就是我想把我的可扩展数组列表放在那里,它可以收集数据并将其转换为字符串格式——但我现在这样做的方式并不正确——我不知何故陷入了困境——我看不到以字符串数组列表的格式收集数据的正确方式(这一点是什么?因为它来自^byteArray
下面是完整的程序——它从HDFS
读取文件,并且——应该(尽管目前不是)将它们输出到字符串数组列表中——最终将使用System.out.println
记录到控制台
// this concatenates output to terminal from hdfs
public static void main(String[] args) throws IOException {
// supply this as input
String uri = args[0];
// reading in from hdfs
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(URI.create(uri), conf);
FSDataInputStream in = null;
// create arraylist for hdfs file to flow into
//List<String> inputLinesObject = new ArrayList<String>();
List<String> inputLinesObject = IOUtils.readLines(in, "UTF-8");
// TODO: how to make this go to a file rather than to the System.out?
try
{
in = fs.open(new Path(uri));
// The way:
IOUtils.copyBytes(in, inputLinesObject, 4096, false);
}
finally{
IOUtils.closeStream(in);
}
# 1 楼答案
使用
ByteArrayOutputStream
,请参见此处: