2013-02-12 71 views
0

我用这个话题:File to byte[] in Java 这里是我的代码:文件到字节数组

try { 
    Path path1 = Paths.get(path + fileName); 
    byte[] fileAsByte = Files.readAllBytes(path1); 
    System.out.println("Byte : " + fileAsByte.toString()); 
} catch (FileNotFoundException e) { 
    System.out.println("File Not Found."); 
    e.printStackTrace(); 
} catch (IOException e1) { 
    System.out.println("Error Reading The File."); 
    e1.printStackTrace(); 
} catch (OutOfMemoryError e3) { 
    System.out.println("Out of Memory"); 
    e3.printStackTrace(); 
    } 

此代码不会触发任何异常,但产量仍:

Byte : [[email protected] 

这对我来说似乎非常无效。我很确定我做了一个愚蠢的错误,但我一直试图解决这个问题已经三个小时了,我可以用一些新的眼光来解决它。

谢谢。

回答

4

您不能直接将数组转换为String,并让人眼可读。它打印出[(意思是“数组”),然后B(对于byte),然后@及其身份哈希码。

为了得到阵列中的字节的列表,使用静态Arrays.toString()方法代替:

System.out.println("Byte : " + java.util.Arrays.toString(fileAsByte)); 

(如果字节表示字符的输出字符串,可以使用@iTech的溶液。)

4

您应该创建一个用您的byte[]初始化的String实例,例如

System.out.println("Byte : " + new String(fileAsByte)); 

您还可以指定编码,例如new String(fileAsBytes,"UTF-8");