字符流

  1. 编码问题
  2. 认识文本和文本文件 java的文本(char)是16位无符号整数,是字符的unicode编码(双字节编码)
    文件是byte byte byte …的数据序列
    文本文件是文本(char)序列按照某种编码方案(utf-8,utf-16be,gbk)序列化为byte的存储结果
  3. 字符流(Reader Writer)---->操作的是文本文本文件
    字符的处理,一次处理一个字符
    字符的底层任然是基本的字节序列
    字符流的基本实现
    InputStreamReader 完成byte流解析为char流,按照编码解析
    OutputStreamWriter 提供char流到byte流,按照编码处理
    FileReader/FileWriter
  4. 字符流的过滤器
    BufferedReader ---->readLine 一次读一行
    BufferedWriter/PrintWriter ---->写一行

字节字符转换流

public class IsrAndOswDemo {

	public static void main(String[] args) throws IOException{
		FileInputStream fis = new FileInputStream("E:\\java学校\\Volume.java");
		//默认项目的编码,操作的时候,要写文件本身的编码格式
		InputStreamReader isr = new InputStreamReader(fis,"utf-8");
		
		FileOutputStream fos = new FileOutputStream("E:\\java学校\\Volume2.java");
		OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
		
		/*int c;
		while((c=isr.read()) != -1) {
			System.out.print((char)c);
		}*/
		
		char[] chars = new char[8*1024];
		int c;
		
		/*批量读取,放入buffer这个字符数组,从第0个位置开始放置,最多放buffer.length个
		  返回的是读到的字符的个数
		*/
		while((c=isr.read(chars,0,chars.length)) != -1) {
			String s = new String(chars,0,c);
			System.out.println(s);
			osw.write(chars,0,c);
			osw.flush();
		}
		
		isr.close();
		osw.close();
	}

}

字符流只文件读写流

public class FrAndFwDemo {

	public static void main(String[] args) throws IOException{
		FileReader fr = new FileReader("E:\\java学校\\Volume.java");
		FileWriter fw = new FileWriter("E:\\java学校\\Volume3.java");
		//FileWriter fw = new FileWriter("E:\\java学校\\Volume3.java",true);
		
		char[] chars = new char[2056];
		int c;
		
		while((c = fr.read(chars,0,chars.length)) != -1) {
			fw.write(chars, 0, c);
			fw.flush();
		}
		
		fr.close();
		fw.close();
	}

}

字符流的过滤器

public class BrAndBwOrPwDemo {

	public static void main(String[] args) throws IOException{
		//对文件进行读写操作
		BufferedReader br = new BufferedReader(
			new InputStreamReader(
					new FileInputStream("E:\\java学校\\Volume.java")));
		
		/*BufferedWriter bw = new BufferedWriter(
			new OutputStreamWriter(
					new FileOutputStream("E:\\java学校\\Volume3.java")));*/
		
		PrintWriter pw = new PrintWriter("E:\\java学校\\Volume4.java");
		
		String s;
		while((s = br.readLine()) != null) {
			System.out.println(s);//一次读一行,并不能识别换行
			//bw.write(s);
			//单独写出换行操作
			/*bw.newLine();
			bw.flush();*/
			pw.println(s);
			//pw.flush();
		}
		
		br.close();
		//bw.close();
		pw.close();
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值