IO之字符流

在程序中一个字符等于两个字节。

1、字符输出流:Writer

抽象类,需要通过FileWriter子类进行实例化

public FileWriter(File file) throws IOExcrption

【Writer类的常用方法】

* public  abstract void close(0 throws IOException 关闭输出流

* public void write(String str) throws IOExcrption 将字符串输出

* public void write(char[] cbuf) throws IOException 将字符数组输出

* public abstaract void flush(0 throws IOEXception 强制清空缓存

实例:向文件中写入数据

public class WriterDemo {
	public static void main(String[] args) {
		File f = new File("D:"+File.separator+"test.txt");
		try {
			FileWriter writer = new FileWriter(f);
			String str = "FileWriter";	
			//与OutputStream的区别就是不用将字符串变成数据,可以直接输出字符串
			writer.write(str);
			writer.close();			
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
}

向文件中追加内容,和OutputStream一样的方法:

public class WriterDemo {
	public static void main(String[] args) {
		File f = new File("D:"+File.separator+"test.txt");
		try {
			FileWriter writer = new FileWriter(f,true);
			String str = "\r\nFileWriter";	
			//与OutputStream的区别就是不用将字符串变成数据,可以直接输出字符串
			writer.write(str);
			writer.close();			
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
}

2、字符输入流:reader

抽象类,通过FileReader类进行实例化

【Reader类常用方法】

* public abstract void close() throws IOException 关闭输出流

* public int  read() throws IOExcrption 读取单个字符

public int read (char [] cbuf) throws IOExcrption  将内容读取字符数组中,返回读入的长度

public class ReaderDemo {
	public static void main(String[] args) {
		File file = new File("d:"+File.separator+"test.txt");
		try {
			FileReader reader = new FileReader(file);
			char c[] = new char[1024];
			int len = reader.read(c);
			reader.close();
			System.out.println("读取内容:"+new String(c,0,len));		
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}

可以通过循环方式进行读写:

public class ReaderDemo {
	public static void main(String[] args) {
		File file = new File("d:"+File.separator+"test.txt");
		try {
			FileReader reader = new FileReader(file);
			char c[] = new char[1024];
			int temp = 0;
			int len =0;
			while ((temp = reader.read())!=-1) {
				c[len] = (char)temp;
				len++;
			}		

			reader.close();
			System.out.println("读取内容:"+new String(c,0,len));		
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值