I have a text file like this:
ids.txt
1000
999
745
123
...
我希望能够读取该文件并将其加载到二维数组中。我期望得到一个类似下面的数组:
Object[][] data = new Object[][] { //
{ new Integer(1000) }, //
{ new Integer(999) }, //
{ new Integer(745) }, //
{ new Integer(123) }, //
...
};
这是我编写的代码:
File idsFile = ... ;
try (Stream<String> idsStream = Files.lines(idsFile.toPath(), StandardCharsets.US_ASCII)) {
Object[][] ids = idsStream
.filter(s -> s.trim().length() > 0)
.toArray(size -> new Object[size][]);
// Process ids array here...
}
运行此代码时,会引发异常:
java.lang.ArrayStoreException: null
at java.lang.System.arraycopy(Native Method) ~[na:1.8.0_45]
at java.util.stream.SpinedBuffer.copyInto(Unknown Source) ~[na:1.8.0_45]
at java.util.stream.Nodes$SpinedNodeBuilder.copyInto(Unknown Source) ~[na:1.8.0_45]
at java.util.stream.SpinedBuffer.asArray(Unknown Source) ~[na:1.8.0_45]
at java.util.stream.Nodes$SpinedNodeBuilder.asArray(Unknown Source) ~[na:1.8.0_45]
at java.util.stream.ReferencePipeline.toArray(Unknown Source) ~[na:1.8.0_45]
...
如何解决这个异常?
new Integer(1000)
?而且你想要一个[][]
,其中内部数组始终具有length == 1
? - Boris the SpiderObject [][ ]
作为输入。 - Stephan