io--文件内容的复制
2024-09-04 11:21:41
public class CopyTextTest_2 { private static final int BUFFER_SIZE = 1024;
public static void main(String[] args) { FileReader fr = null;
FileWriter fw = null;
try {
//创建字节输入流,选择要读取数据的文件
fr = new FileReader("IO流_2.txt");
//创建字节输出流,选择要写入数据的文件
fw = new FileWriter("copytest_2.txt");
//创建一个临时容器,用于缓存读取到的字符。
char[] buf = new char[BUFFER_SIZE];//这就是缓冲区。
//定义一个变量记录读取到的字符数,(其实就是往数组里装的字符个数 )
int len = 0;
//循环从输入流中取出的数据
while((len=fr.read(buf))!=-1){
//每读取一次,即写入文件输入流,读多少写多少
fw.write(buf, 0, len);
}
} catch (Exception e) {
// System.out.println("读写失败");
throw new RuntimeException("读写失败");
}finally{
if(fw!=null)
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
if(fr!=null)
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} }
使用缓冲流:
public static void main(String[] args) {
FileReader fr=null;
FileWriter fw=null;
BufferedReader br=null;
BufferedWriter bw=null;
try {
fr=new FileReader("e://test.txt");
fw=new FileWriter("e://newFile.txt");
br=new BufferedReader(fr);
bw=new BufferedWriter(fw); String line=null;
while ((line=br.readLine())!=null) {
bw.write(line);
}
} catch (IOException e) { e.printStackTrace();
}finally{
try {
//要关闭缓冲流,这样数据才会被刷新然后写入到新的文件中
bw.close();
br.close();
} catch (IOException e) { e.printStackTrace();
}
} }
最新文章
- yii2 的request get pos请求 基本用法示例
- display:none 与 opacity:0
- SQL Server性能影响的重要结论
- 夺命雷公狗---Thinkphp----12之文章的增删改查(图片上传和关联查询)
- weblogic部署ssh2应用出现异常
- cometd的js端代码
- Python 3 集合基础和概念!
- linux 内核的futex pi-support,即pi-futex使用rt_mutex委托
- Spring DelegatingFilterProxy解析
- 阿里深度兴趣网络模型paper学习
- Android Stutio中使用java8的Lambda表达式
- python 视频转成代码视频
- Lintcode105 Copy List with Random Pointer solution 题解
- Vue之项目搭建
- 解决HTTP status code is not handled or not allowed
- mbpoll Test FreeModbus TCP Demo
- MySql union与order by
- 详细解读大数据分析引擎Pig&;PigLatin语句
- Parted 手册
- SPI中的极性CPOL和相位CPHA