1

所以我写了这段代码,将文件从一个文件夹复制到另一个文件夹!它适用于 .mp3 .wav .jpeg.jpg 文件

但它不适用于 .png 文件!(图像被破坏或丢失一半)

有没有办法可以编辑代码是否适用于 .png 文件?如果没有,我该如何复制它们?

我还想补充一个问题!当前代码可以在我的计算机上运行,​​因为我的计算机上D:\\move\\1\\1.mp3存在此路径!

如果我将我的程序转换为 .exe 文件并将其提供给其他人,它就不起作用,因为他的计算机上不存在该路径!所以而不是这条线

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

我想做类似的东西

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

代码 :

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

}
4

1 回答 1

2

试试这个方法:

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

或者,如果您想使用 Java 输入/输出,请尝试以下方式:

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();
}
于 2020-04-28T08:18:18.373 回答