java如何通过字符流实现文件拷贝
作者:吹吹风会发光
时间:2023-04-26
浏览:1
通过字符流实现文件拷贝使用字符流只能拷贝文本文件/***通过字符流实现文件的拷贝**@paramsourcePath源文件路径*@paramtargetPath目标文件路径*/publicstaticvoidcopyFileByReaderAndWriter(StringsourcePath,StringtargetPath){//源文件路径Filesource=newFile(sourcePath);//目标文件路径Filetarget=newFile(targetPath);//如果源文件不存在则不能
本文目录
通过字符流实现文件拷贝
使用字符流只能拷贝文本文件
/**
* 通过字符流实现文件的拷贝
*
* @param sourcePath 源文件路径
* @param targetPath 目标文件路径
*/
public static void copyFileByReaderAndWriter(String sourcePath, String targetPath) {
//源文件路径
File source = new File(sourcePath);
//目标文件路径
File target = new File(targetPath);
//如果源文件不存在则不能拷贝
if (!source.exists()) {
return;
}
//如果目标文件目录不存在则创建
if (!target.getParentFile().exists()) {
target.getParentFile().mkdirs();
}
FileReader in = null;
FileWriter out = null;
try {
//字符输入流和字符输出流
in = new FileReader(source);
out = new FileWriter(target);
char[] c = new char[1024];
int temp = 0;
//每次读取1024个字符
while ((temp = in.read(c)) != -1) {
//输出到文件
out.write(c, 0, temp);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
作者最新文章
漫蛙官网线路更新提醒通知
2026-11-24 14:09
AO3官网中文入口最新地址公布
2026-11-19 10:44
AO3镜像网站一键入口链接
2026-11-18 13:04
手机修复PDF失败怎么办?PDF电脑修复怎么选
2026-11-18 12:23
腾讯文档误删内容怎么恢复历史版本 找回方法
2026-11-17 13:42
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































