【发布时间】:2015-05-03 11:59:13
【问题描述】:
我正在尝试将字节数组写入文件并随后读取它们。重要的是,我写入的字节数组与读取的字节数组相同。我尝试了这里建议的一些方法 (File to byte[] in Java)。但是,当我应用它们时,我最终会读取我最初编写的不同数组。
这是我尝试过的:
import java.io.File;
//import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
import org.apache.commons.io.*;
public class FileConverter {
public static void ToFile(byte[] bytes, String pathName) throws IOException{
FileOutputStream f = new FileOutputStream(pathName);
f.write(bytes);
f.close();
}
public static byte[] ToBytes(String pathName) throws IOException{
//Path path = Paths.get(pathName);
//byte[] bytes = Files.readAllBytes(path);
//FileInputStream f = new FileInputStream(pathName);
//byte[] bytes = IOUtils.toByteArray(f);
File file = new File(pathName);
byte[] bytes = FileUtils.readFileToByteArray(file);
return bytes;
}
}
我的测试课:
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
public class FileConverterTest {
@Test
public void leesSchrijf() throws IOException{
String test = "test";
String pathName = "C://temp//testFile";
byte[] bytes = test.getBytes();
FileConverter.ToFile(bytes, pathName);
Assert.assertEquals(bytes, FileConverter.ToBytes(pathName));
}
}
每当我执行测试类时,我的结果都会发生变化,并且数组永远不会匹配。 例如java.lang.AssertionError: 预期: 但是是:(第一次执行)
java.lang.AssertionError: 预期: 但是是:(下一次执行)
我对测试类还很陌生,而且我不是 Java 天才。所以我想知道我是否做错了什么。如果没有,有没有办法在将字节数组写入文件时保留它?
【问题讨论】:
-
看着你的错误信息,我开始怀疑转换是否有问题。事实上bytes.length=test.length()。试试这个。一个字节就是一个字符。
-
你没有比较字节数组的内容。