0
I’m running a test with a simple code, but it’s going wrong. I simply want to get the contents of a binary file that is an image (jpg), and save it again under another name.
My code is this:
String content = null;
FileInputStream in = new FileInputStream(new File("C:\\farol.jpg"));
StringBuilder builder = new StringBuilder();
int ch;
while ((ch = in.read()) != -1) {
builder.append((char) ch);
}
in.close();
content = builder.toString();
BufferedWriter out = new BufferedWriter(new FileWriter("C:\\farolNOVO.jpg"));
out.write(content);
out.close();
The image "farolNOVO.jpg" is being created, with the correct dimension and the same size as the original, only it gets all weird.
Someone’s been through this trouble?
OBS 1: This code is working for files . txt OBS 2: I’m using java 1.6 (I can’t update it for compatibility reasons with other things around here)
Doing other tests around here, I found one that worked in parts:
String FILE_ORINNAL = "C:\\farol.jpg";
String FILE_NOVO = "C:\\faro_novo.jpg";
InputStream inputStream = new FileInputStream(FILE_ORINNAL);
OutputStream outputStream = new FileOutputStream(FILE_NOVO);
int byteRead;
while ((byteRead = inputStream.read()) != -1) {
outputStream.write(byteRead);
}
The problem is that this is reading and passing directly to the outputStream. I wanted to do a "getContentFileBinary" method that returns to the binary container string. Then I want to do another method "getContentFileBinaryBase64"
That’s my ultimate goal.
Do you want to keep the old file? You need to read the contents of the file?
– Felipe Marinho
The old file for me doesn’t matter. I’m just trying to read a binary file and saving it for testing. This code is a piece of my script, then I’ll code it into Base64 and do other things. But I’m already having trouble at this point.
– AndersonSouza
Do not post the answer in the body of the question, use the reply button and add to the answer your solution
outputStream.write(content.getBytes("ISO-8859-1")); Esse "ISO-8859-1" resolveu meu problema!
– Guilherme Nascimento