Getting a binary file and saving it again

Asked

Viewed 1,096 times

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.

inserir a descrição da imagem aqui

The original image is this: inserir a descrição da imagem aqui

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?

  • 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.

  • 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!

3 answers

1

Probably reading is missing something, you can try reading the contents using this:

import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

...

Path p = FileSystems.getDefault().getPath("", "C:\\farol.jpg");
byte [] fileData = Files.readAllBytes(p);

And then record:

import java.io.FileOutputStream;

...

FileOutputStream stream = new FileOutputStream("C:\\farolNOVO.jpg");
try {
    stream.write(fileData);
} finally {
    stream.close();
}

I ran the test with this:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.FileOutputStream;

public class Foo
{
    public static void main(String args[]) throws IOException
    {
        Path caminho = Paths.get("c:\\farol.jpg");

        byte [] fileData = Files.readAllBytes(caminho);

        FileOutputStream stream = new FileOutputStream("c:\\farolNOVO.jpg");
        try {
            stream.write(fileData);
        } finally {
            stream.close();
        }
    }
}

Copying files

However I find something quite redundant to have to read the content and copy the file, since it will be an indentical copy, if this is really the goal, just copy I suggest use the File.copy.

  • static long copy(InputStream in, Path target, CopyOption... options)

    Copies bytes from an inputstream to a file

  • static long copy(Path source, OutputStream out)

    Copies bytes from a file to an outputstream.

  • static Path copy(Path source, Path target, CopyOption... options)

    Copies a file to another file

Example of using to overwrite if there is already a file in the folder:

import java.nio.file.StandardCopyOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;

...

Path caminho = Paths.get("c:\\farol.jpg");
Path destrino = Paths.get("c:\\farolNOVO.jpg");

Files.copy(caminho, destrino, StandardCopyOption.REPLACE_EXISTING);
  • I guess I don’t have the class "Path"

  • @Andersonsouza java.nio.file Available since the Java7

  • I don’t have this: import java.nio.file.......

  • @Andersonsouza what is your Java? You must be very outdated

  • Yes, but I’m using java 1.6 :(

  • I commented at the end of my question there, I think I’ll put at the beginning kkkk because java 1.6 eh very old already

Show 1 more comment

0

Java 6 or less

In versions earlier or equal to Java 6 you can do so:

File original = new File("c:\\farol.jpg");
if(!original.exists()) {
    throw new IOException("O arquivo especificado não existe!");    
}

File novo = new File("c:\\farolNOVO.jpg");
if(novo.exists()) {
    throw new IOException("Já existe um arquivo com esse nome");
 }

original.renameTo(novo);

Java 7

In versions equal to or larger than Java 7 you can do so:

File original = new File("c:\\farol.jpg");
if(!original.exists()) {
    throw new IOException("O arquivo especificado não existe!");    
}

File novo = new File("c:\\farolNOVO.jpg");
if(novo.exists()) {
    throw new IOException("Já existe um arquivo com esse nome");
 }

Files.move(original.toPath(), 
        novo.toPath(), 
        StandardCopyOption.REPLACE_EXISTING);
  • thanks for helping, but I need to get the contents of the file. This was my test example. Then I will convert it to Base64. So I need to get the file contents

0


My problem was at the time of creating the file. After I used "ISO-8859-1" it worked.

outputStream.write(content.getBytes("ISO-8859-1")); 

That "ISO-8859-1" solved my problem!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.