尝试使用 Java 代码通过 cmd 复制文件

Trying to copy files with cmd using Java code

这是代码,程序运行但功能未执行。是否可以像这样复制 Java 中的文件,或者我应该使用其他方法?如果是这样,任何参考资料都会有所帮助。

import java.io.*;
import java.util.*;
import java.lang.*;
 public class test
{
    public static void main(String[] args) 
    {

        String path = "cmd /C cd C:/xamppy/htdocs/fuzzy/includes/xxxxx"; 


        String command = "cmd /C copy \"C:/xamppy/htdocs/fuzzy/includes/xxxxx/lifelesson.jpg\" \"C:/xamppy/htdocs/fuzzy/searcheditems\"";       
        try{
            Runtime.getRuntime().exec(path);
        Runtime.getRuntime().exec(command);
        }
        catch(IOException e)
        {
            System.out.println(e);
        }
    }
}

在java中,您可以使用 FileOuputStream 和 FileInputStream 复制文件。 这是简短的演示:

public static void main(String[] args) throws IOException {
        File file = new File("C:\createtable.sql");
        File copy = new File("C:\copy.sql");

        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(copy);

        byte[] buffer = new byte[1024];

        int length;
        // copy the file content in bytes
        while ((length = fis.read(buffer)) > 0) {

            fos.write(buffer, 0, length);

        }

        fis.close();
        fos.close();

        System.out.println("File is copied successful!");
    }

首先它创建了两个文件 filecopy。字节数组 buffer 保存从 FileInputStream 读取并写入 FileOutputStream.

的文件内容