Java SE中字符的输入输出流

字符适合处理中文数据
在进行IO处理时,若处理图片、音乐、文字都可以使用字节流,只有处理中文时,才会考虑字符流
字符流的操作,无论是输入还是输出,数据都优先保存在缓存中

字符输出流:Writer(抽象类,若要操作文件要使用FileWriter子类)
public abstract class Writer implements Appendable,Closeable,Flushable
直接输出字符串的方法:
public void write(String str)

public class Main {
	public static void main(String[] args) throws IOException {
	File file = new File("C:"+File.separator+"Users"+File.separator+"CGX~LL"+File.separator+"Desktop"+File.separator+"singer.txt");
	if(!file.getParentFile().exists()) {//保证其父目录存在
		file.getParentFile().mkdirs();
		}
	String str = "我学了javaSE";
	Writer writer = new FileWriter(file);
	writer.write(str);
	writer.close();
	//如果不关闭流,数据无法输出到终端  使用writer.flush() (强行输出缓存区数据)
	//writer.flush();
	}
}

字符输入流:Reader
Reader是一个抽象类,进行文件读取,使用FileReader子类
Reader中没有方法可以直接读取字符串,只能通过字符数组进行读取操作

public class Main {
	public static void main(String[] args) throws IOException {
	File file = new File("C:"+File.separator+"Users"+File.separator+"CGX~LL"+File.separator+"Desktop"+File.separator+"singer.txt");
	if(file.exists()) {
		Reader reader = new FileReader(file);
		char[] data = new char[1024];
		//将数据读取到字符数组中
		reader.read(data);
		//将字符数组转化为字符串
		String str = new String(data);//默认全部转换
		System.out.println(str);
		//关闭流
		reader.close();
		}
	}
}

查看字节流请点击下方链接:

https://blog.csdn.net/ChenGX1996/article/details/81663931

猜你喜欢

转载自blog.csdn.net/ChenGX1996/article/details/81664781