文件到字节 [] 读取不正确

file to byte[] reading incorrectly

我是saving/reading一个字节数组。当我打印保存的字节时,它们都是正确的值,但是当我读取它们时,每个保存的字节之间有 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 文件中的数据(用Notepad++打开) 空行, 0, 0, 0, 0, 28, 1, 1, 28, 2, 1, $, 1, 1, 31, 0, 2, ï¿¿, 0, 2 早些时候由于某种原因读取了未写入文件的负数。

只需使用标准库 (import java.nio.file.Files;)。

byte[] tmpData = Files.readAllBytes(file.toPath());

Files.write(file.toPath(), bytes);