將字串轉換為影像時遇到問題。轉換字串影像后,它說檔案格式無效。
public class FileExample {
public static void main(String[] args) throws IOException {
File file = new File("G:\\designpatterns\\image002.jpg");
FileInputStream fis = new FileInputStream("G:\\designpatterns\\image002.jpg");
byte bytes[]= new byte[(int)file.length()];
fis.read(bytes);
String rawString = new String(bytes);
FileOutputStream fos = new
FileOutputStream("G:\\designpatterns\\image001.jpg");
fos.write(rawString.getBytes());
fis.close();
fos.close();
}
}
uj5u.com熱心網友回復:
AString不是任意位元組的合適容器。
當您嘗試String從位元組創建一個時,就像您在這里所做的那樣:
String rawString = new String(bytes);
然后類的建構式String將使用字符編碼來解釋這些位元組并嘗試將它們轉換為字符。
因為影像檔案的位元組不代表用某種字符編碼編碼的文本,所以這將失敗。
不要將 aString用作任意二進制資料的容器。
如果您需要以字符的形式存盤二進制資料,例如影像檔案的內容,請使用Base64 encoding之類的東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/468468.html
上一篇:PHP通過嵌套鍵查找陣列項
