2012-05-17 30 views
1

這基本上是我想要做的。文件 - >字節[] - >字符串 - >字節[] - >文件轉換

我想帶一個文件

把它變成一個字節數組

把它變成一個字符串

儲存於一個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); 
     } 

    } 
} 

http://pastebin.com/699yuE8f

+2

將來,請將代碼直接發佈到您的問題中。 –

+0

我總是弄錯了,然後格式看起來很可怕。 – OmniOwl

+4

使用代碼示例將其與文本區分開來。 – Venki

回答

2

你的方法完全忽略編碼,這不是一件好事。字符是而不是等於或等於字節。

如果你必須這樣做你所描述的順序,然後像這樣創建的字符串:

String intermediateString = new String(theByteArray, 
             theSameEncodingTheFileWasCreatedWith); 

同樣,當你的字符串轉換回字節,得到這樣的字節:

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

但除此之外,使用字符串有什麼意義呢?爲什麼不直接將字節存儲到數據庫中?

+0

我以前從來沒有在數據庫中存儲字節,所以我想嘗試將它存儲爲更熟悉的東西,用於狗屎和笑聲。但是我之前已經把一個字節數組轉換成了一個文件,而不必考慮編碼,所以..yeah。 – OmniOwl

+0

將字節數組保存爲文件時,您無需關心編碼。字節是字節。當字符串處於進程中間時,需要進行編碼。字節 - >字符串和字符串 - >字節意味着你必須處理編碼。 – QuantumMechanic

+0

@Vipar:它試圖存儲什麼樣的字節有很大的不同。 QuantumMechanic是正確的,'char'!='byte'!您是否試圖將*文件中的文本*存儲到數據庫中,或者您是否試圖存儲*文本數據以使您能夠重新構建文件*?如果你想要後者,爲什麼不把實際字節存儲爲BLOB? –

1

您只需搞砸字符串創建的,你不看bosbuf

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

否則我不相信它會起作用或者它是一個很好的解決方案。爲什麼你不能把它存儲在數據庫中?

+0

因爲我想將它作爲純文本存儲,而不是物理文件。 – OmniOwl

+1

@Vipar:將任意二進制數據存儲爲字符串是一個衆所周知的問題。正常的解決方案是使用[base64](http://en.wikipedia.org/wiki/Base64)之類的東西,而不是發明自己的編碼。 –

0

您共享的代碼是恕我直言,因爲它必須是更復雜。

如果你只是對字符串表示感興趣,你爲什麼要在字節級讀取文本?

我傾向於使用InputStreamReader來閱讀文件。這可以讓你直接操作角色。

+0

不需要苛刻。我只是在黑暗中拍攝。感謝您的輸入。 – OmniOwl

+0

我不確定你爲什麼認爲我的回答很糟糕。我雖然直接回答,但直接讓你明白這一點。代碼越長,代碼編寫者獲得的更多可能性就越小。 – Robert

相關問題