尝试使用Java代码用cmd复制文件
下面是代码,程序运行,但函数没有执行。可以像这样用Java复制文件吗?或者我应该使用不同的方法吗?如果是这样,任何参考资料都会有所帮助尝试使用Java代码用cmd复制文件,java,runtime,exec,Java,Runtime,Exec,下面是代码,程序运行,但函数没有执行。可以像这样用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/fu
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中,您可以使用FileOutStream和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!");
}
首先,它创建两个文件
file
和copy
。字节数组buffer
保存从FileInputStream
读取并写入FileOutputStream
的文件内容。如果这样做,还可以使用它来处理异常并正确释放资源。只是告诉@SaumyaSharma一些好的做法。根据这段代码,文件内容从一个文件复制到另一个文件。但是,我没有任何这样的临时文件。那么,有没有一种方法可以使用java创建新文件,然后复制其中的内容呢?createNewFile
可以使用file
类的方法