我有很多包含图片和视频的图形文件。我想将它们存储在arrayList中。大多数文件都是图片。只有一些是低分辨率短视频。
我选择使用byte []的arrayList。以下代码用于测试步骤 我将图像文件加载到ArrayList中。 然后我尝试将包含的byte []的副本写入文件。我之前已成功使用此命令将独立的byte []写入文件,因此我知道它有效。
问题是我需要从ArrayList读取整个字节数组作为数组。我无法弄清楚如何做到这一点。
我在Java API中找到了.toArray命令,但我无法弄清楚这种情况的语法。 API对我来说并不清楚。 我试过了:
byte[] b = new byte[1000];
ary[0].toArray(byte[] b);
和
ary[0].toArray();
但是我无法让他们工作。
package test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
public class testArrayListByteCopy {
public static void main(String[] args){
System.out.println("Running Array of byte arrays copy test");
ArrayList < byte[] > ary; //define the arrays
//create an ArrayList with 3x byte[] arrays
ary = new ArrayList<byte[]>(3);
//load up one of them
try {
ary.add(Files.readAllBytes(Paths.get("/home/test1.png")));
}
catch (IOException e) {
e.printStackTrace();
}
// save byte[] into a file
Path path = Paths.get("/home/testSave.png");
// The next line fails. The error message says array expected but arrayList byte[] found. Illegal start of expression.
//Files.write(path, ary[0].toArray() ,StandardOpenOption.CREATE);
// This line works based on the answers below.
Files.write(path, arrayTo.get(0),StandardOpenOption.CREATE);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
您应该写ary.get(0)
而不是ary[0].toArray()
,因为ArrayList
类型不能与[]
订阅。只有内置数组类型为(T[]
)。