Dhia Djobbi
Dhia Djobbi

Reputation: 1289

How can i copy png files? and Dynamic directory path

So I wrote this code that copies a file from a folder to another one! it works fine with .mp3 .wav .jpeg.jpg files

but it doesn't work properly with .png files! (the image is destroyed or half of it is missed)

Is there a way I can edit the code is it works with .png files? if no, how can I copy them?

I also want to add another question! the current code works on my computer because of this path D:\\move\\1\\1.mp3 exist on my computer!

if I convert my program to .exe file and give it to someone else it doesn't work because that path doesn't exist on his computer! so instead of this line

    FileInputStream up = new FileInputStream("D:\\move\\1\\images\\1.jpg");

i wanna make something like

    FileInputStream up = new FileInputStream(findAppFolder+"\\images\\1.jpg");

code :

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {

    public static void main(String[] args) throws IOException {

        FileInputStream up = new FileInputStream("D:\\move\\1\\images\\1.jpg");
        FileOutputStream down = new FileOutputStream("D:\\move\\2\\images\\2.jpg");
        BufferedInputStream ctrl_c = new BufferedInputStream(up);
        BufferedOutputStream ctrl_v = new BufferedOutputStream(down);
        int b=0;
        while(b!=-1){
            b=ctrl_c.read();
            ctrl_v.write(b);
        }
        ctrl_c.close();
        ctrl_v.close();
    }

}

Upvotes: 1

Views: 910

Answers (1)

Samim Hakimi
Samim Hakimi

Reputation: 725

Try this way:

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

Path source=Paths.get("abc.png");
Path destination=Paths.get("abcNew.png");
Files.copy(source, destination);

Or if you want to use with Java input/output try this way:

public void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer all byte from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

Upvotes: 2

Related Questions