有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java文件>字节[]>字符串>字节[]>文件转换

这基本上就是我想做的

我要拿个文件

将其转换为字节数组

把它变成一根绳子

将其存储在MySQL表中

检索字符串

将其转换回字节数组

将其重新转换为文件

现在,我为您准备了一些代码,我尽可能地对其进行注释。我的问题是,我在代码末尾得到的文件显示不正确。这是丢失的信息。这是一个文本文件,所以我应该能够判断文件是否完整

就我所见,看起来我只得到了文件的最后一部分,而不是整个文件。我敢肯定,在这次转换中,我把事情搞砸了。如果您有关于如何更有效地进行转换和检索的建议(仍然要记住数据库和所有这些),请让我也知道

代码如下所示

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


共 (3) 个答案

  1. # 1 楼答案

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

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

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

  2. # 2 楼答案

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

    如果必须按照所描述的顺序执行,则通过以下方式创建字符串:

    String intermediateString = new String(theByteArray,
                                           theSameEncodingTheFileWasCreatedWith);
    

    同样,当您将字符串转换回字节时,得到如下字节:

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

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

  3. # 3 楼答案

    您共享的代码比原来复杂得多

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

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