通过字符流实现文件拷贝
使用字符流只能拷贝文本文件
/**
* 通过字符流实现文件的拷贝
*
* @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();
}
}
}以上就是Java实现文件拷贝:使用字符流进行操作的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号