从byte []到String的精确转换

Fac*_*con -2 java string bytearray file

数组byte []包含照片的完美逐字节副本,当我尝试将byte []转换为String并使用它写入文件时,它会失败.

我需要转换为字符串以便稍后通过套接字发送它.

我的每个连接的处理程序都有一个Socket(sock),PrintWriter(out)和BufferedReader(in),然后我将Socket与PrintWriter和BufferedReader相关联.有了这个,我发送和接收字符串out.println和in.readLine.

我怎样才能解决这个问题?

测试代码:

// getPhoto() returns byte[]
String photo = new String(getPhoto());

// Create file
DataOutputStream os = new DataOutputStream(new FileOutputStream("out1.jpg"));
// This makes imperfect copy of the photo
os.writeBytes(photo);

//This works perfectly basically it copies the image through byte[]
//os.write(getPhoto());

// Close the output stream
os.close();
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

数组byte []包含照片的完美逐字节副本,当我尝试将byte []转换为String并使用它写入文件时,它会失败.

是.那是因为字符串用于文本,而照片不是文本.只是不要将它转换为字符串.你也不需要DataOutputStream:

OutputStream os = new FileOutputStream("out1.jpg");
try {
    os.write(getPhoto());
} finally {
    os.close();
}
Run Code Online (Sandbox Code Playgroud)