Java 文件转存:使用 InputStream 和 OutputStream 实现
可以使用 Java 中的 FileInputStream 和 FileOutputStream 来实现文件转存,具体实现可以参考以下代码:
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
String sourceFilePath = 'source.txt'; // 源文件路径
String targetFilePath = 'target.txt'; // 目标文件路径
try (InputStream inputStream = new FileInputStream(sourceFilePath);
OutputStream outputStream = new FileOutputStream(targetFilePath)) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
System.out.println('文件转存成功!');
} catch (IOException e) {
e.printStackTrace();
}
}
}
这段代码将源文件中的内容读入到一个字节数组中,然后将字节数组中的内容写入到目标文件中,从而实现了文件的转存。
原文地址: https://www.cveoy.top/t/topic/jsJX 著作权归作者所有。请勿转载和采集!