gpt4 book ai didi

java - 文件 -> byte[] -> 字符串 -> byte[] -> 文件转换

转载 作者:行者123 更新时间:2023-11-29 05:59:44 26 4
gpt4 key购买 nike

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

我想要一个文件

将其转化为字节数组

把它变成一个字符串

将其存储在 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

最佳答案

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

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

String intermediateString = new String(theByteArray,
theSameEncodingTheFileWasCreatedWith);

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

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

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

关于java - 文件 -> byte[] -> 字符串 -> byte[] -> 文件转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10639680/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com