【发布时间】:2018-02-19 15:13:14
【问题描述】:
我有许多包含图像和视频的图形文件。我想将这些存储在 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();
}
}
}
【问题讨论】:
-
等等,你想在内存中存储视频?您知道实际需要多少空间吗?
-
视频文件大小在 50kB 到 200kB 之间,因此将它们存储在内存中没有问题。
标签: java arrays arraylist type-conversion