-1
파일 문서를 가져 와서 비트 표현으로 변환 한 다음 나중에 유사한 표현의 문자열로 변환하려고합니다. 원래의 비트 배열과 마침내 원래의 최종 문서로 이동합니다.파일을 바이트 배열로 변환 한 다음 문자열을 바이트 배열로 변환 한 다음 원본 파일
여기 내 코드입니다. 그러나 생성 된 파일은이 경우 이미지로 볼 수 없습니다.
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());
}
내가 잘못하고있는 것을 가리키는 데 도움이 되셨습니까? 내 코드를 올바르게 작동하는 것이 중요 할 수 있습니다.
어떤 도움이되지 않습니까? functionnality 당 메소드에 있어야합니다. 이것은 작동하는 것을 테스트하는 것이 더 쉽고 그렇지 않은 테스트는 더 쉬울 것입니다. 그리고 간단한 텍스트 파일로 시작해야합니다 ... jpg는 단계별로 값을 확인하는 것이 더 복잡합니다. – AxelH
자바 doc :'String (byte [] bytes) 플랫폼의 기본 charset **을 사용하여 지정된 바이트 배열 **을 ** 디코딩 **하여 새 String을 구성합니다.이 내용이 내용을 수정한다고 생각합니다. – Fefux
바이트를 String으로 변환합니다. 그 (것)들을 부패하거나 바꾼다. C에서 문자열에 바이트를 저장할 수는 있지만 Java에서는 그렇게 할 수 없습니다. Java에서는 바이트를 바이트 배열 또는 [ByteBuffer] (http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html)에 저장합니다. 여기서 문자열을 사용하지 마십시오. – VGR