我想创建两种方法。一个应该将数组列表存储到缓存中,另一个应该从缓存中检索数组列表。我尝试过的代码如下:
public class ByteConverter<T> {
public byte[] write_to_byte_array(ArrayList<T> list,File file){
// write to byte array
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e1) {
Log.d("file not found", "file not found", e1);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(baos);
for (T element : list) {
try {
out.writeUTF((String) element);
} catch (IOException e) {
Log.d("Error converting List to byte array", "Error converting List to byte array", e);
}
}
byte[] bytes = baos.toByteArray();
int len1 = 0;
while (len1 < bytes.length) {
try {
fos.write(bytes, 0, len1);
len1++;
} catch (IOException e) {
e.printStackTrace();
}
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
}
public String read_to_byte_array(byte[] bytes) throws IOException{
// read from byte array
String element = null;
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream in = new DataInputStream(bais);
while (in.available() > 0) {
element = in.readUTF();
}
return element;
}
}
但是,上述方法不会将任何内容写入文件。我不知道为什么。谁能帮我?此外,我在这一行采取了 ClassCastException:
out.writeUTF((String) element);