【问题标题】:How to read the ByteArray from the file in Java?如何从 Java 文件中读取 ByteArray?
【发布时间】:2013-09-28 04:42:27
【问题描述】:

我在一个文件中写了一个ByteArray。然后我试图从同一个文件中读取ByteArray ..

public static void main(String[] args) throws Exception {

        //.. some code

        writeFile(allWrittenBytesTest);

        readFile();

}

/**
 * Write the file in Java
 * @param byteArray
 */
public static void writeFile(byte[] byteArray) {

    try{
        File file = new File("bytearrayfile");

        boolean success = file.delete();

        if(!success) {
            System.out.println("not able to delete the file");
        }

        FileOutputStream output = new FileOutputStream(file);
        IOUtils.write(byteArray, output);           
    } catch (Exception ex) {
        ex.printStackTrace();
    }   

现在,我无法理解如何从同一个文件中读取 ByteArray?下面是我的 readFile 方法-

public static void readFile() {

    BufferedReader reader = null;
    try {

        File file = new File("bytearrayfile");

        reader = new BufferedReader(new FileReader(file));

        String line = null;
        while ((line = reader.readLine()) != null) {

            // this doesn't work I know but not sure how to read that?
            DataInputStream inTest = new DataInputStream(new ByteArrayInputStream(line));

            // some other code to deserialize that ByteArray

        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

【问题讨论】:

  • 您不需要删除。无论如何,创建 FileOutputStream 都会创建一个新文件。
  • @EJP:谢谢你的提示..

标签: java file bytearray


【解决方案1】:

如果你使用的是 org.apache.commons.io 包,你可以使用:

        bytes = FileUtils.readFileToByteArray(new File(file));  

例子:

    public static void readFile() {

        BufferedReader reader = null;
        try {
            File file = new File("bytearrayfile");
            reader = new BufferedReader(new FileReader(file));          
            byte[] bytes = FileUtils.readFileToByteArray(file); 
            System.out.println(new String(bytes, "UTF-8").toCharArray());       

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
}

我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    公共类 FileToByteArray {

    public static void main(String a[]){
    
        String fileName = "C:/MyFile.txt";
        InputStream is = null;
        try {
            is = new FileInputStream(fileName);
            byte content[] = new byte[2*1024];
            int readCount = 0;
            while((readCount = is.read(content)) > 0){
                System.out.println(new String(content, 0, readCount-1));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try{
                if(is != null) is.close();
            } catch(Exception ex){
    
            }
        }
    }
    

    }

    【讨论】:

    • 'readCount-1' 不正确,应该是 'readCount'。无论如何,仅仅代码不是答案。你需要解释一下。 -1
    【解决方案3】:

    您的问题很有趣,因为如果您与流的概念进行交互,您几乎总是得到字节而不是字符串。您使用了将文件读取到字符串的习惯用法:

        reader = new BufferedReader(new FileReader(file));
    
        String line = null;
        while ((line = reader.readLine()) != null) {
              // ...code to use each line of a file in string format! 
        }
    

    但这实际上是为了将文件逐行读取为字符串。

    您实际上可以只使用普通的 FileInputStream,但这次使用另一个习惯用法(或者您使用如上所述的 Apache Commons):

     fis = new FileInputStream(filePath);
     int currentBytes = 0
     while((currentBytes=fis.read()) > -1){
       //...code to use the file stream byte by byte
     }
    

    您可以将整数(一个字节 2^8 的值介于 0 和 255 之间)放入一个字节数组中。现在的问题是您不知道从流中接收到多少字节(文件有多大),因此您无法确定生成的字节数组的大小。一种解决方案是使用列表(如 ArrayList),然后使用 list.toArray(new byte[list.size()]) 方法将其转换为 byte[],但我不太喜欢这个。还有一个名为 ByteArrayOutputStream 的类可以透明地为您处理 byte[] 的大小调整。

    代码如下:

     fis = new FileInputStream(filePath);
     int currentBytes = 0
     ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream()
     while((currentBytes=fis.read()) > -1){
       byteBuffer.write(currentBytes)
     }
     byte[] yourByteArray = byteBuffer.toByteArray()
    

    代码未经测试,是从我的大脑中编写的。我希望它有效。

    【讨论】:

    • 它没有。除非您知道数据是文本,否则您根本不应该使用 Readers 和 Writers。否则,您可能会损坏数据。未经测试的代码不可能是答案。 -1
    • @EJP:很好,我一直认为 BufferedReader 是一个缓冲区,专为所有类型的数据(也只是字节)而设计,但似乎 Readers 和 Writers 是为文本数据设计的。好吧,我调整了答案,只使用普通流。
    猜你喜欢
    • 1970-01-01
    • 2019-02-17
    • 2023-03-27
    • 1970-01-01
    • 2021-08-18
    • 2017-01-13
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多