【问题标题】:How can i copy png files? and Dynamic directory path如何复制png文件?和动态目录路径
【发布时间】:2020-08-11 23:46:00
【问题描述】:

所以我编写了这段代码,将文件从一个文件夹复制到另一个文件夹! 它适用于 .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();
    }

}

【问题讨论】:

  • 我不完全确定它是否能解决问题,但您也许可以尝试使用 PathFiles 类(来自“新”java.nio 包)复制文件而不是普通文件流。
  • ..而且,我无法重现 - png 被上述代码复制,没有问题

标签: java file copy bufferedinputstream bufferedoutputstream


【解决方案1】:

试试这个方法:

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

【讨论】:

  • 我尝试使用您的路径代码,但它不起作用。他无法解析符号“复制”
  • 您是否尝试“刷新”您的项目然后“清理”?如果它不起作用,请尝试更新您的 IDE。
  • 是的,我做到了,我尝试了你的两个解决方案,但都没有工作..
  • 尝试导入:import java.nio.file.*;希望这个工作
  • ofc 我导入它.. 我认为问题出在代码中,而不是在 IDE 或命名空间中..
猜你喜欢
  • 2012-01-25
  • 1970-01-01
  • 2021-07-09
  • 2012-10-02
  • 1970-01-01
  • 2015-03-04
  • 1970-01-01
  • 1970-01-01
  • 2011-09-01
相关资源
最近更新 更多