简体   繁体   English

文件 - > byte [] - > String - > byte [] - >文件转换

[英]File -> byte[] -> String -> byte[] -> File Conversion

This is basically what I am trying to do. 这基本上就是我想要做的。

I wanna take a File 我想拿一个文件

Turn it into a Byte Array 把它变成一个字节数组

Turn it into a String 把它变成一个字符串

Store it in a MySQL Table 将其存储在MySQL表中

Retrieve the String 检索字符串

Turn it back into a Byte Array 将其转回字节数组

Turn it back into a File 把它变回文件

Now, I have some code for you, which I tried to comment as best as I could. 现在,我有一些代码给你,我试着尽可能地评论。 My problem is, that the file I get at the end of this code, doesn't come out right. 我的问题是,我在这段代码的末尾得到的文件并不正确。 It's missing information. 它缺少信息。 It's a text file, so I should be able to tell whether the file is complete or not. 这是一个文本文件,所以我应该能够判断文件是否完整。

As far as I can see, it looks like I only get the last part of the file, and not the entire file. 据我所知,看起来我只得到文件的最后一部分,而不是整个文件。 I am pretty sure I messing something up badly somewhere in this conversion. 我很确定我在这个转换中的某个地方搞砸了一些东西。 If you got suggestions on how to do this conversion and retrieval more efficiently (Still keeping the Database and all that in mind), please let me know as well! 如果您有关于如何更有效地进行此转换和检索的建议(仍然保留数据库和所有这些),请告诉我们!

The code is listed below 代码如下所示

import java.io.*;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

public class main {
    public static void main(String[] args) {
        // The file we want to save.
        File f = new File("build.xml");
        try {
            // Make it into a byte array first
            FileInputStream fis = new FileInputStream(f);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            try {
                for(int readNum; (readNum = fis.read(buf)) != -1;) {
                    bos.write(buf, 0, readNum);
                    System.out.println("read " + readNum + " bytes,");
                }
                StringBuilder s = new StringBuilder();
                // Now we simulate making it into a String, for easier storage
                // in a database.
                for(byte b : buf) {
                    // for debugging
                    s.append(b).append(",");
                    System.out.print(b +",");
                }
                // Now we want to retrieve the file from the database as a string
                File someFile = new File("build2.xml");
                FileOutputStream fos = new FileOutputStream(someFile);
                // We count how many bytes there are in this string.
                // One byte per Token.
                StringTokenizer st = new StringTokenizer(s.toString(),",");
                buf = new byte[st.countTokens()];
                int i = 0;
                StringBuilder t = new StringBuilder();
                // Now we parse out all Bytes from the string, and put them into
                // the prepared byte array.
                while(st.hasMoreTokens()) {
                    byte b = Byte.parseByte(st.nextToken());
                    System.out.print(b + ",");
                    buf[i] = b;
                    i++;
                    // for debugging
                    t.append(b).append(",");
                }
                // Here I print true if both strings are exactly the same
                // which they should be, which means that the bytes are intact
                // before and after conversion.
                System.out.println("\n" +(t.toString().equals(s.toString()) ? true : false));
                // Here we would make the physical file on the machine.
                fos.write(buf);
                fos.flush();
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

http://pastebin.com/699yuE8f http://pastebin.com/699yuE8f

Your approach is totally ignoring encodings, which is not a good thing. 你的方法完全忽略了编码,这不是一件好事。 Characters are not equal to or equivalent to bytes. 字符等于或等于字节。

If you have to do it in the sequence you describe, then create the string by something like this: 如果你必须按照你描述的顺序进行,那么通过以下方式创建字符串:

String intermediateString = new String(theByteArray,
                                       theSameEncodingTheFileWasCreatedWith);

Likewise, when you convert the string back into bytes, get the bytes like this: 同样,当您将字符串转换回字节时,获取如下字节:

byte[] bytesToSave = intermediateString.getBytes(theSameEncodingTheFileWasCreatedWith);

But besides any of that, what's the point of using the string at all? 但除此之外,使用字符串有什么意义呢? Why not just store the bytes right into the database? 为什么不直接将字节存储到数据库中?

You simply messed up the string creation, and you don't read the bos but the buf . 你只是弄乱了字符串创建,你没有阅读bos而是buf

            for(byte b : >>buf<<) {
                // for debugging
                s.append(b).append(",");
                System.out.print(b +",");
            }

Otherwise I am not convinced that it will work or it is a good solution. 否则我不相信它会起作用或者它是一个很好的解决方案。 Why can't you just store it simply in the database? 为什么不能将它简单地存储在数据库中?

The code you shared is IMHO more complicated as it had to be. 你分享的代码是恕我直言,因为它必须是更复杂的。

Why do you read your text on byte-level if you are only interested in it's String representation? 如果您只对字符串表示感兴趣,为什么要在字节级读取文本?

I would prefer to read the file using an InputStreamReader . 我更喜欢使用InputStreamReader读取文件。 That allows you to directly operate on characters. 这允许您直接操作字符。

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

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