首页 文章

从byte []到String的精确转换

提问于
浏览
-2

数组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();

2 回答

  • 8

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

    是 . 那个's because strings are for text, and a photo isn't文字 . 只需要 DataOutputStream t需要 DataOutputStream ,或者:

    OutputStream os = new FileOutputStream("out1.jpg");
    try {
        os.write(getPhoto());
    } finally {
        os.close();
    }
    
  • 0

    不要将二进制数据加载到String中 . 如果它不是tetx,就不要使用String

相关问题