java之FileReader和FileWriter的简单用法,案例:字符流的拷贝

FileReader的简单使用

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * 以后读文件时,都纯文本文件,使用FileReader这个类,因为不用考虑乱码 
 *
 */

public class Demo01 {
public static void main(String[] args) throws IOException {
	//FileReader
	/**
	 * FileReader 用于读取字符
	 */
	
	
	//1.创建对象
	FileReader fr=new FileReader("a.txt");
	
	//2.读取数据,
	/**
	 * reader.read():先读取到字节数据,然后转为字符
	 */
	
	int len=0;
	while ((len=fr.read())!=-1) {
		System.out.println((char)len);
	} 
	
}
}

FileWriter的简单使用
package com.zifu;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/**
 * FileWriter掌握write方法即可
 *
 */
public class Demo02 {
public static void main(String[] args)throws IOException {
	//FileWrite写入字符流
	
	//案例:使用FileWiter往一个文件a.txt写内容
	
	//1.创建writer
	FileWriter fw=new FileWriter("a.txt");
	Scanner input=new Scanner(System.in);
	//2.写内容
	System.out.println("请输入内容:");
	while (true) {
		String content=input.nextLine();
		fw.write(content);
		fw.write("\r\n");
		if(content.equals("quit")) {
			break;
		}
	}
	
	//3.关闭流
	
	fw.close();
}
}

案例:字符流的拷贝
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Demo03 {
public static void main(String[] args)throws IOException{
	//案例:字符流的拷贝
	//思路:用FileReader读字符,用FileWriter写字符
	//test1();
	test2();//缓冲思想,效率更好
	
	
}
//方法一
public static void test1() throws FileNotFoundException, IOException {
	//1.创建“读取流”对象
	FileReader fr=new FileReader("a.txt");
	
	//2.创建“写入流”对象
	FileWriter fw=new FileWriter("b.txt");
	//3.读取写入
	int c=0;
	while ((c=fr.read())!=-1) {
		fw.write(c);
	}
	
	//4.关闭流
	fw.close();
	fr.close();
}


//方法二

public static void test2() throws FileNotFoundException, IOException {
	//1.创建“读取流”对象
		FileReader fr=new FileReader("a.txt");
		
		//2.创建“写入流”对象
		FileWriter fw=new FileWriter("b.txt");
		
		//3.读取写入【缓冲思想】
		char[] buf=new char[8*1024];
		
		int len=0;
		while ((len=fr.read(buf))!=-1) {
			fw.write(buf);
		}
		
		
		//4.关闭流
		fw.close();
		fr.close();
}

}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值