Java I/O (Input/Output)——文件字节流
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileByteStreamCopy {
public static void main(String[] args) {
// 源文件和目标文件路径
String sourcePath = "source.txt";
String destPath = "dest.txt";
try (
FileInputStream fis = new FileInputStream(sourcePath);
FileOutputStream fos = new FileOutputStream(destPath)
) {
byte[] buffer = new byte[1024]; // 缓冲数组
int length;
while ((length = fis.read(buffer)) > 0) { // 读取文件到缓冲数组
fos.write(buffer, 0, length); // 从缓冲数组写入文件
}
System.out.println("文件复制成功!");
} catch (IOException e) {
System.out.println("文件复制失败!");
e.printStackTrace();
}
}
}
这段代码使用了Java的FileInputStream
和FileOutputStream
来复制文件。它使用了try-with-resources
语句来自动关闭流,并使用了缓冲区来提高文件读写的效率。代码简洁,注重异常处理,是学习I/O操作的良好示例。
评论已关闭