IO-FileReader、FileWriter类

向文件中写入数据

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

public class IOOperation {
	public static void main(String[] args) throws IOException {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		Writer out = new FileWriter(f);
		String str = "hello";
		out.write(str);
		out.close();
	}
}

运行结果:在文件中写入hello


其实这个例子和之前的例子没什么区别,只是你可以直接输入字符串,而不需要你将字符串转化为字节数组。如果想向文件中追加内容,可以将上面的声明out的哪一行换为:

Writer out = new FileWriter(f, true);

从文件中读内容

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class IOOperation {
	public static void main(String[] args) throws IOException {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		Reader in = new FileReader(f);
		char[] charArr = new char[1024];
		int len = in.read(charArr);
		in.close();
		System.out.println("读取长度:" + len);
		System.out.println(new String(charArr, 0, len));
	}
}

运行结果:

-----------------------------------------------------------------------

读取长度:5

hello

-----------------------------------------------------------------------


采用循环读取

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class IOOperation {
	public static void main(String[] args) throws IOException {
		String fileName = "D:" + File.separator + "hello.txt";
		File f = new File(fileName);
		Reader in = new FileReader(f);
		char[] charArr = new char[1024];
		int count = 0;
		int temp = 0;
		while((temp = in.read()) != -1) {
			charArr[count++] = (char)temp;
		}
		in.close();
		System.out.println(new String(charArr));
	}
}

运行结果:hello

 

使用字节流好还是字符流好呢?

答案是字节流。首先因为硬盘上的所有文件都是以字节的形式进行传输或者保存的,包括图片等内容。但是字符只是在内存中才会形成的,所以在开发中,字节流使用广泛。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值