我正在保存/读取字节数组。当我打印要保存的字节时,它们都是正确的值,但是当我读取它们时,在保存的每个字节之间都有3个随机负数,并且在字节的末尾还有一堆额外的随机值,并且所有负数数字不见了。
阅读代码:
byte[] tmpData = new byte[(int) file.length()];
try {
tmpData = IOUtil.readFully(file);
} catch (IOException e) {
e.printStackTrace();
}
IOUtil.readFully
public static byte[] readFully(File file) throws IOException {
Checks.notNull(file, "File");
Checks.check(file.exists(), "Provided file does not exist!");
InputStream is = new FileInputStream(file);
Throwable var2 = null;
byte[] var8;
try {
long length = file.length();
if (length > 2147483647L) {
throw new IOException("Cannot read the file into memory completely due to it being too large!");
}
byte[] bytes = new byte[(int)length];
int offset = 0;
int numRead;
for(boolean var7 = false; offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0; offset += numRead) {
;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
is.close();
var8 = bytes;
} catch (Throwable var12) {
var2 = var12;
throw var12;
} finally {
$closeResource(var2, is);
}
return var8;
}
写作代码:
BufferedWriter writer = new BufferedWriter(new FileWriter(path, false));
int[] data = new int[] { 19,0,0,0,0,28,1,1,28,2,1,36,1,1,31,0,2,-1,0,2 }
for(int bytes : data) { writer.write(bytes); }
读取字节: 10,0,10,0,10,0,10,0,10,28,10,1,10,1,10,28,10,2,10,1,10,36,10,1,10, 1,10,31,10,0,10,2,10,-17,-65,-65,10,0,10 文件中的数据(使用记事本++打开) 空行,0,0,0,0,28,1,1,28,2,1,$,1,1,1,31,0,2,ï¿¿,0,2 出于某种原因,以前会读取未写入文件的负数。
答案 0 :(得分:3)
只需使用标准库(import java.nio.file.Files;
)。
byte[] tmpData = Files.readAllBytes(file.toPath());
和
Files.write(file.toPath(), bytes);