【发布时间】:2017-04-14 20:25:57
【问题描述】:
我正在尝试(在 Java 中)获取文件文档,然后将其转换为 bitArray,然后转换为类似表示的字符串,然后返回原始位数组,最后转换为原始最终文档。
这是我的代码,但在这种情况下,生成的文件无法查看图像。
try {
File file = new File("C:/Users/dkimigho/Downloads/kenyapowerlogo.jpg");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//create FileInputStream which obtains input bytes from a file in a file system
//FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1;) {
//Writes to this byte array output stream
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
} catch (IOException ex) {
Logger.getLogger(ARRAYBITStoPDF.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] bytes = bos.toByteArray();
System.out.println("byte1");
for (int i = 0; i < bytes.length; i++) {
System.out.print(bytes[i]);
}
//We have the bytes now convert to String
String stringbytearray=new String(bytes);
System.out.println("stringbytearray: "+stringbytearray);
//We have the bytes now convert to String
byte[] content = stringbytearray.getBytes();
System.out.println("byte2");
for (int i = 0; i < content.length; i++) {
System.out.print(content[i]);
}
int size = bytes.length;
InputStream isfilecontent = null;
byte[] b = new byte[size];
isfilecontent = new ByteArrayInputStream(content);
//writing the downloaded data into a PDF file
FileOutputStream fileOutputpdf = new FileOutputStream("C:/Users/dkimigho/Downloads/mykenyapowerlogo.jpg");
/* use binary I/O to prevent line based operation messing with the encoding.*/
byte[] buf2 = new byte[2048];
int b_read = 0;
while ( (b_read = isfilecontent.read(buf2)) > 0) {
fileOutputpdf.write(buf2, 0, b_read);
}
fileOutputpdf.flush();
//closed the output stream
fileOutputpdf.close();
} catch (IOException e) {
// handle IOException
System.out.println(e.getMessage());
}
任何帮助指出我做错了什么?将我的代码更正为有效的代码可能很重要。
【问题讨论】:
-
任何帮助指出什么不起作用?你应该有每个功能的方法。这将更容易测试什么有效,什么无效。你应该从一个简单的文本文件开始......一个jpg更复杂,逐步检查值。
-
Java doc :
String(byte[] bytes) Constructs a new String by **decoding** the specified array of bytes **using the platform's default charset**.我认为这会修改您的内容 -
将字节转换为字符串会破坏/更改它们。您可以在 C 中将字节存储在字符串中,但在 Java 中不能这样做。在 Java 中,您将字节存储在字节数组或ByteBuffer 中。这里根本不要使用字符串。
-
您的意图是什么,您的用例是什么?试图将 JPEG 文件的字节解释为字符串没有任何意义。或者你的意思是你想要一个字节的字符串表示,比如 Base64,它用于通过文本协议传输二进制数据?
-
是的,我想要一个字节的字符串表示形式,例如 Base64,它用于通过使用 htttp 但在 xml 节点中传输二进制数据