简体   繁体   English

如何从Java中的文件读取ByteArray?

[英]How to read the ByteArray from the file in Java?

I have written a ByteArray in a file. 我已经在文件中写入了ByteArray And then I am trying to read that ByteArray back from that same file.. 然后,我尝试从同一文件中读取该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();
    }   

Now, I am not able to understand how to read that ByteArray back from that same file? 现在,我不明白如何从同一文件读取该ByteArray? Below is my readFile method- 下面是我的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();
    }
}

Well if you are using org.apache.commons.io package you could use just use: 好吧,如果您使用的是org.apache.commons.io软件包,则可以使用:

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

Example: 例:

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

I hope this helps. 我希望这有帮助。

Your question is funny because if you interact with the concept of streams you almost always get bytes instead of an string. 您的问题很有趣,因为如果您与流的概念进行交互,则几乎总是获得字节而不是字符串。 You used the idiom of reading a file to a string: 您使用了将文件读取为字符串的惯用法:

    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! 
    }

But this actually is made to read a file line by line to a string. 但这实际上是为了逐行读取文件到字符串。

You can actually use just the plain FileInputStream but this time with another idiom (or you use Apache Commons like described above): 实际上,您实际上可以只使用普通的FileInputStream,但是这次可以使用另一个习惯用法(或者您使用上述的Apache Commons):

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

You could just put the integer (value between 0 and 255 for one byte 2^8) into an byte array. 您可以将整数(一个字节2 ^ 8的值在0到255之间)放入字节数组。 Now the problem is you don't know how many bytes you receive from the stream (how big the file is) and therefore you can't determine the size of your resulting byte array. 现在的问题是,您不知道从流中接收了多少字节(文件有多大),因此无法确定所得字节数组的大小。 One solution is to use a list (like ArrayList) and afterwards convert it to an byte[] with the list.toArray(new byte[list.size()]) method but I don't like this so much. 一种解决方案是使用列表(如ArrayList),然后使用list.toArray(new byte [list.size()])方法将其转换为byte [],但我对此不太喜欢。 There is an other class called ByteArrayOutputStream which handles the resizing of an byte[] transparently for you. 还有一个称为ByteArrayOutputStream的其他类,它为您透明地处理byte []的大小调整。

The code would look like: 代码如下所示:

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

The code is not tested, it is written from my brain. 该代码未经测试,是由我的大脑编写的。 I hope it works. 我希望它能起作用。

public class FileToByteArray { 公共类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){

        }
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM