1

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();
    }

}
Dhia Djobbi
  • 1,176
  • 2
  • 15
  • 35
  • I'm not entirely sure if it will solve the issue but you perhaps could try using `Path` and `Files` classes (from "new" `java.nio` package) for copying files instead of plain streams. – Amongalen Apr 28 '20 at 08:17
  • ..and, I cannot reproduce - [png](https://www.google.com/url?sa=i&url=https%3A%2F%2Fde.wikipedia.org%2Fwiki%2FDatei%3ASARS-CoV-2_without_background.png&psig=AOvVaw08RTCUzFeinkx6WHfJQUOO&ust=1588148396187000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCMCnsvzXiukCFQAAAAAdAAAAABAD) gets copied by the above code, with no issues – xerx593 Apr 28 '20 at 08:24

1 Answers1

2

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();
}
Samim Hakimi
  • 705
  • 8
  • 22