首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >File -> byte[] -> String -> byte[] ->文件转换

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

Stack Overflow用户
提问于 2012-05-18 00:29:02
回答 3查看 6.1K关注 0票数 1

这基本上就是我想要做的。

我想要一份文件

将其转换为字节数组

将其转换为字符串

将其存储在MySQL表中

检索字符串

将其重新转换为字节数组

将其重新转换为文件

现在,我为你准备了一些代码,我尽我所能对它们进行了注释。我的问题是,我在这段代码末尾得到的文件不能正确输出。遗漏了一些信息。这是一个文本文件,所以我应该能够判断该文件是否完整。

据我所知,我似乎只得到了文件的最后一部分,而不是整个文件。我很确定我在这个转换过程中搞砸了一些东西。如果你有关于如何更有效地进行这种转换和检索的建议(仍然牢记数据库和所有这些),请让我知道!

代码如下所示

代码语言:javascript
复制
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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-05-18 00:38:38

您的方法完全忽略了编码,这不是一件好事。字符是而不是等于或等于字节的

如果你必须按照你描述的顺序来做,那么就用下面这样的方式来创建字符串:

代码语言:javascript
复制
String intermediateString = new String(theByteArray,
                                       theSameEncodingTheFileWasCreatedWith);

同样,当您将字符串转换回字节时,可以像这样获取字节:

代码语言:javascript
复制
byte[] bytesToSave = intermediateString.getBytes(theSameEncodingTheFileWasCreatedWith);

但除此之外,使用字符串的意义到底是什么?为什么不直接将字节存储到数据库中呢?

票数 2
EN

Stack Overflow用户

发布于 2012-05-18 00:35:57

您只是搞乱了字符串的创建,而且您读取的不是bos而是buf

代码语言:javascript
复制
            for(byte b : >>buf<<) {
                // for debugging
                s.append(b).append(",");
                System.out.print(b +",");
            }

否则,我不相信它会起作用,或者它是一个好的解决方案。为什么你不能简单地把它存储在数据库中呢?

票数 1
EN

Stack Overflow用户

发布于 2012-05-18 00:41:10

你分享的代码要复杂得多。

如果你只对它的字符串表示感兴趣,为什么你要在字节级上阅读你的文本?

我更喜欢使用InputStreamReader读取文件。允许您直接对字符进行操作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10639680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档