在Java中复制文件可以使用以下方法:
- 使用Java IO库中的FileInputStream和FileOutputStream类进行复制操作。示例代码如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopy {
public static void main(String[] args) {
File sourceFile = new File("source.txt");
File destFile = new File("dest.txt");
try (FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
System.out.println("File copied successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 使用Apache Commons IO库中的FileUtils类进行复制操作。示例代码如下:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class FileCopy {
public static void main(String[] args) {
File sourceFile = new File("source.txt");
File destFile = new File("dest.txt");
try {
FileUtils.copyFile(sourceFile, destFile);
System.out.println("File copied successfully!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
这两种方法都是常用的文件复制方法,你可以根据自己的需求选择适合的方法来实现文件复制操作。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/984775.html