如何从Java中的文件读取ByteArray? [英] How to read the ByteArray from the file in Java?

查看:90
本文介绍了如何从Java中的文件读取ByteArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在文件中写入了 ByteArray 。然后我试图从同一文件中读取 ByteArray

I have written a ByteArray in a file. And then I am trying to read that ByteArray back from that same file..

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方法-

Now, I am not able to understand how to read that ByteArray back from that same file? Below is my readFile method-

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();
    }
}


推荐答案

如果您使用的是org.apache.commons.io包,则可以使用以下方法:

Well if you are using org.apache.commons.io package you could use just use:

        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();
        }
}

我希望这会有所帮助。

这篇关于如何从Java中的文件读取ByteArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆