這基本上是我想要做的。文件 - >字節[] - >字符串 - >字節[] - >文件轉換
我想帶一個文件
把它變成一個字節數組
把它變成一個字符串
儲存於一個MySQL表
檢索字符串
打開它回到一個字節陣列
T它回到一個文件
現在,我有一些代碼給你,我試圖評論盡我所能。我的問題是,我在這段代碼的末尾得到的文件沒有出來。它缺少信息。這是一個文本文件,所以我應該能夠判斷文件是否完整。
據我所見,它看起來像我只得到文件的最後部分,而不是整個文件。我很確定我在這個轉換中的某個地方糟糕透頂。如果您對如何更有效地完成此轉換和檢索(仍然保留數據庫及所有內容)有任何建議,請讓我知道!
的代碼下面列出
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);
}
}
}
將來,請將代碼直接發佈到您的問題中。 –
我總是弄錯了,然後格式看起來很可怕。 – OmniOwl
使用代碼示例將其與文本區分開來。 – Venki