簡體   English   中英

從文件讀取字節或向文件寫入字節

[英]Reading and writing bytes from/to a file

我正在嘗試將字節數組寫入文件並隨后讀取它們。 重要的是,我寫入的字節數組必須與我讀取的字節數組相同。 我嘗試了一些建議的方法( 在Java中是File to byte [] )。 但是,當我應用它們時,我最終會讀取最初編寫的另一個數組。

這是我嘗試過的:

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:預期:<[B @ a3a7a74>,但是:: <[B @ 53d5aeb>(首次執行)

java.lang.AssertionError:預期:<[B @ 29643eec>,但是是:<[B @ 745f0d2e>(下次執行)

我是測試類的新手,而且我不是Java天才。 所以我想知道我是否做錯了什么。 如果不是,是否有一種在將字節數組寫入文件時保留字節數組的方法?

在Junit測試中,您正在比較對象引用而不是對象內容。 也許您想要實現的是比較字節數組的內容。 您可以通過導入import org.junit.Assert;來使用Assert.assertArrayEquals import org.junit.Assert; 例如

Assert.assertArrayEquals(bytes, FileConverter.ToBytes(pathName));

看來Assert.assertEquals使用euqlas方法比較對象,但是數組沒有覆蓋其equals方法,它們從Object類繼承它,並且它使用==運算符比較引用,而不是對象狀態。

要比較數組的內容,您需要遍歷它們並比較它們的元素。

您也可以使用Arrays.equals(arr1, arr2)幫助程序方法來為您完成此工作。 如果要比較多維數組,還可以使用Arrays.deepEquals

你可以像這樣使用它

Assert.assertTrue(Arrays.equals(arr1, arr2));

或以更清潔的方式

Assert.assertArrayEquals(arr1, arr2);

還實現了Serializable接口,並在FileUtils類中生成一個私有的靜態最終長serialVersionUID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM