2016-07-15 21 views
-2

好吧,所以我知道這會被要求一個體面的數量,但是這有些不同。我有一個程序需要一個圖像文件(或用戶選擇的任何輸入文件)並將其轉換爲一個字節數組,然後將其放入一個字符串中。但是,當將字符串數組(每個包含一個字節的元素)轉換回字節數組時,它告訴我無法將字符串(或者當我嘗試使用Integer.parseInt時的整數)轉換爲字節對象。任何想法發生了什麼? 這是數組中的字節串輸出的一個例子的文件已被讀取後:需要將字節數組轉換爲可傳輸的字符串並返回(這不是重複的)

|1|1|1|0|96|0|96|0|0|-1|-37|0|67|0|2|1|1|2|1|1|2|2|2|2|2|2|2|2|3|5|3|3|3|3|3|6|4|4|3|5|7|6|7|7|7|6|7|7|8|9|11|9|8|8|10|8|7|7|10|13|10|10|11|12|12|12|12|7|9|14|15|13|12|14|11|12|12|12|-1|-37|0|67|1|2|2|2|3|3|3|6|3|3|6|12|8|7|8|12|12|12|12|12|12|12|12|12|12|12|12|12|12|12| 

是的,它是正常分裂 這裏是我的代碼:

import java.io.IOException; 
import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.util.*; 

public class SmallBinaryFiles{ 

    public static void main(String aArgs) throws IOException{ 

     Scanner sc = new Scanner(System.in); 
     SmallBinaryFiles binary = new SmallBinaryFiles(); 
     System.out.println("1. Send file"); 
     System.out.println("2. Recieve file"); 

     if(sc.nextInt() == 1){ 
      System.out.println("Name of file (with Extension and proper capitalization)"); 
      byte[] bytes = binary.readSmallBinaryFile(sc.nextLine()); 
      log("Small - size of file read in:" + bytes.length); 
      for(int x = 0;x < bytes.length; x++){ 
       System.out.print(bytes[x] + "|"); 
      } 
     }else{ 
      System.out.println("Name of file to write (with extension)"); 
      String fileName = sc.nextLine(); 
      System.out.println("Please input raw data:"); 
      String rawData = sc.nextLine(); 
      String delims = "[|]+"; 
      String[] tempArray = rawData.split(delims); 
      byte[] bytes = new byte[tempArray.length]; 
      for(int x = 0; x < tempArray.length;x++){ 
       bytes[x] = tempArray[x].toByte(); 
      } 
      binary.writeSmallBinaryFile(bytes, fileName); 
     } 
    } 

    byte[] readSmallBinaryFile(String aFileName) throws IOException{ 
     Path path = Paths.get(aFileName); 
     return Files.readAllBytes(path); 
    } 

    void writeSmallBinaryFile(byte[] aBytes, String aFileName) throws IOException{ 
     Path path = Paths.get(aFileName); 
     Files.write(path, aBytes); 
    } 

    private static void log(Object aMsg){ 
     System.out.println(String.valueOf(aMsg)); 
    } 
} 

任何幫助(我不知道爲什麼代碼做到了,對此感到抱歉)

+1

首先,重新格式化這個。其次,如果你需要把'String'變成'byte []',那麼'String.getBytes()'是你正確的方法。 – ifly6

+2

*爲什麼*要將字節數組轉換爲這種格式的字符串?這聽起來像一個可怕的想法。爲什麼不使用base64? –

+0

Binary不是文字 –

回答

1

但是,當將字符串數組(每個包含一個字節的元素)轉換回字節數組時,它會告訴我在我不能轉換一個字符串(或者當我嘗試Integer.parseInt時的整數)到一個字節對象。任何想法發生了什麼?

嗯,沒有這樣的方法,如String.toByte(),並不清楚你如何嘗試使用Integer.parseInt()。這應該工作:

bytes[x] = (byte) Integer.parseInt(tempArray[x]); 

雖然這是一個可怕的編碼方案 - 我強烈要求你使用base64或十六進制代替。

相關問題