一、IO流之字符流
字符流出现的原因:由于字节流操作中文不是特别方便,转换流。
字符流: 字符流 = 字节流 + 编码表
注解:String类中的编码和解码问题
编码: 就是把字符串转换成字节数组
- 把一个字符串转换成一个字节数组
- public byte[] getBytes();使用平台的默认字符集将此 String编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
- public byte[] getBytes(String charsetName) 使用指定的字符集将此 String 编码为 byte 序列,并将结果存储到一个新的 byte 数组中。
- 解码: 把字节数组转换成字符串
- public String(byte[] bytes): 通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
- public String(byte[] bytes, String charsetName) 通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。
- 使用什么字符集进行编码,那么就是使用什么字符集进行解码
(一)字符流的5种写数据的方式
A: 方法概述
public void write(int c) 写一个字符
public void write(char[] cbuf) 写一个字符数组
public void write(char[] cbuf,int off,int len) 写一个字符数组的 一部分
public void write(String str) 写一个字符串
public void write(String str,int off,int len) 写一个字符串的一部分
B:案例演示: 字符流的5种写数据的方式
(二)字符流的2种读数据的方式
A: 方法概述
public int read() 一次读取一个字符
public int read(char[] cbuf) 一次读取一个字符数组 如果没有读到 返回-1
A:案例演示: 字符流的2种读数据的方式
InputStreamReader in = new InputStreamReader(new FileInputStream("c.txt"));
char[] chars = new char[1000];
//一次读取一个字符数组
// int len = in.read(chars); //返回值是读取到的有效的字符个数
//一次读取一个字符数组的一部分
int len = in.read(chars,0,522); //返回值是读取到的有效的字符个数
System.out.println(len);
for (char cha : chars) {
System.out.println(cha);
}
in.close();
(三)转换流
(1)OutputStreamWriter的使用
A:OutputStreamWriter的构造方法
OutputStreamWriter(OutputStream out):根据默认编码(GBK)把字节流的数据转换为字符流
OutputStreamWriter(OutputStream out,String charsetName):根据指定编码把字节流数据转换为字符流
B:案例演示: OutputStreamWriter写出数据
(2)InputStreamReader的使用
A:InputStreamReader的构造方法
InputStreamReader(InputStream is):用默认的编码(GBK)读取数据
InputStreamReader(InputStream is,String charsetName):用指定的编码读取数据
B:案例演示: InputStreamReader读取数据
字符流复制文本文件方式1
public class CopyFile {
public static void main(String[] args) throws IOException {
//方式1:一次读取一个字符,写入一个字符,来复制文本文件
InputStreamReader in = new InputStreamReader(new FileInputStream("MyTest.java"));
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("E:\\MyTest.java"));
int len=0;
while ((len=in.read())!=-1){
out.write(len);
out.flush();//字符流记得刷一下
}
System.out.println("复制完成");
in.close();
out.close();
}
}
public class CopyFile2 {
public static void main(String[] args) throws IOException {
//一次读取一个字符数组,来复制文本文件
//方式2:一次读取一个字符,写入一个字符,来复制文本文件
InputStreamReader in = new InputStreamReader(new FileInputStream("MyTest.java"));
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("E:\\MyTest.java"));
int len = 0;
char[] chars = new char[1024];
while ((len = in.read(chars)) != -1) {
out.write(chars, 0, len);
out.flush();
}
//释放资源
in.close();
out.close();
}
}
FileWriter和FileReader复制文本文件方式2
A:FileReader和FileWriter的出现
转换流的名字比较长,而我们常见的操作都是按照本地默认编码实现的,所以,为了简化我们的书写,转换流提供了对应的子类。
FileWriter
FileReader
B:案例演示: FileWriter和FileReader复制文本文件
字符流便捷类: 因为转换流的名字太长了,并且在一般情况下我们不需要制定字符集,于是java就给我们提供转换流对应的便捷类
(四)字符缓冲流
(1)基本使用
A:案例演示: BufferedWriter写出数据 高效的字符输出流
B:案例演示: BufferedReader读取数据 高效的字符输入流
高效的字符流
高效的字符输出流: BufferedWriter
构造方法: public BufferedWriter(Writer w)
高效的字符输入流: BufferedReader
构造方法: public BufferedReader(Reader e)
(2)字符缓冲流复制文本文件
(3)字符缓冲流的特殊功能
A:字符缓冲流的特殊功能
BufferedWriter: public void newLine():根据系统来决定换行符 具有系统兼容性的换行符
BufferedReader: public String readLine():一次读取一行数据 是以换行符为标记的 读到换行符就换行 没读到数据返回null
包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null
B:案例演示: 字符缓冲流的特殊功能
BufferedReader in = new BufferedReader(new FileReader("MyTest.java"));
BufferedWriter out = new BufferedWriter(new FileWriter("E:\\MyTest3.java"));
int len = 0;
char[] chars = new char[1024];
while ((len = in.read(chars)) != -1) {
out.write(chars, 0, len);
out.flush();
}
//释放资源
in.close();
out.close();
(4)字符缓冲流的特殊功能复制文本文件
//BufferedReader 里面有一个特有的方法 String readLine () 一次取一行文本
BufferedReader in = new BufferedReader(new FileReader("MyTest.java"));
//BufferedWriter 里面有一个特有的方法 void newLine () 写入一个换行符,具有平台兼容性
BufferedWriter out = new BufferedWriter(new FileWriter("E:\\MyTest4.java"));
//采用读取一行写人一行来复制文件
String line = null;
while ((line = in.readLine()) != null) { //读取不到返回 null
out.write(line);
out.newLine();
out.flush();
}
in.close();
out.close();
举例:(1)把集合中的数据存储到文本文件
分析:把ArrayList集合中的字符串数据存储到文本文件
a创建一个ArrayList集合
b: 添加元素
c: 创建一个高效的字符输出流对象
d: 遍历集合,获取每一个元素,把这个元素通过高效的输出流写到文本文件中
e: 释放资源
ArrayList<String> list = new ArrayList<>();
list.add("张飞");
list.add("赵云");
list.add("关羽");
list.add("马超");
list.add("黄忠");
//遍历集合,取出数据,写入文本文件
BufferedWriter out = new BufferedWriter(new FileWriter("name.txt"));
for (String s : list) {
//System.out.println(s);
out.write(s);
out.newLine();
//out.write("\r\n");
out.flush();
}
out.close();
(2)把文本文件中的数据存储到集合中
A:案例演示: 需求:从文本文件中读取数据(每一行为一个字符串数据)到集合中,并遍历集合
分析:
* a: 创建高效的字符输入流对象
* b: 创建一个集合对象
* c: 读取数据(一次读取一行)
* d: 把读取到的数据添加到集合中
* e: 遍历集合
* f: 释放资源
BufferedReader in = new BufferedReader(new FileReader("name.txt"));
ArrayList<String> list = new ArrayList<>();
String line = null;
while ((line = in.readLine()) != null) {
list.add(line);
}
System.out.println(list);
(3)随机获取文本文件中的姓名
A:案例演示: 需求:我有一个文本文件,每一行是一个学生的名字,请写一个程序,每次允许随机获取一个学生名称
分析:
a: 创建一个高效的字符输入流对象
b: 创建集合对象
c: 读取数据,把数据存储到集合中
d: 产生一个随机数,这个随机数的范围是 0 - 集合的长度 . 作为: 集合的随机索引
e: 根据索引获取指定的元素
f: 输出
g: 释放资源
BufferedReader in = new BufferedReader(new FileReader("name.txt"));
ArrayList<String> list = new ArrayList<>();
String line = null;
while ((line = in.readLine()) != null) {
list.add(line);
}
// System.out.println(list);
Random random = new Random();
int index = random.nextInt(list.size());
String s = list.get(index);
System.out.println(s);
(4)复制单级文件夹
需求: 复制D:\course这文件夹到E:\course
分析:
a: 封装D:\course为一个File对象
b: 封装E:\course为一个File对象,然后判断是否存在,如果不存在就是创建一个目录
c: 获取a中的File对应的路径下所有的文件对应的File数组
d: 遍历数组,获取每一个元素,进行复制
e: 释放资源
//封装源文件夹
File srcFolder = new File("D:\\test");
//封装目标文件夹
File targetFolder = new File("E:\\test");
if (!targetFolder.exists()) {
targetFolder.mkdirs();
}
copyFiles(srcFolder, targetFolder);
}
private static void copyFiles(File srcFolder, File targetFolder) throws IOException {
//进行文件的复制
//1.获取源文件下的所有文件
File[] files = srcFolder.listFiles();
for (File f : files) {
//一个个复制
copySingleFile(f, targetFolder);
}
}
private static void copySingleFile(File f, File targetFolder) throws IOException {
FileInputStream in = new FileInputStream(f);//D:\\test\\a.avi
//E:\\test\\a.avi
System.out.println(targetFolder+ f.getName());
FileOutputStream out = new FileOutputStream(targetFolder +"\\"+ f.getName());
int len2 = 0;
byte[] bytes = new byte[1024 * 10];
while ((len2 = in.read(bytes)) != -1) {
out.write(bytes, 0, len2);
}
in.close();
out.close();
(5)删除多级目录及文件
public class MyTest2 {
public static void main(String[] args) {
//删除多级目录
File file = new File("E:\\demo");
deleteFolder(file);
}
private static void deleteFolder(File file) {
//获取此目录下所有的文件或者目录
File[] files = file.listFiles();
for (File f : files) {
if (f.isFile()) {
f.delete();
} else {
deleteFolder(f);
}
}
file.delete();//删除自身这个空文件夹
}
}
(6)复制指定目录下指定后缀名的文件并修改名称
需求: 复制D:\demo目录下所有以.java结尾的文件到E:\demo .并且将其后缀名更改文.png
//1.封装源文件夹
File srcFolder = new File("D:\\test");
//2.封装目标文件夹
File targetFolder = new File("E:\\test");
if (!targetFolder.exists()) {
targetFolder.mkdirs();
}
//复制文件夹
copyFolder(srcFolder, targetFolder);
System.out.println("复制完成!");
}
private static void copyFolder(File srcFolder, File targetFolder) throws IOException {
//获取源文件夹下所有的文件,复制并改名
File[] files = srcFolder.listFiles();
for (File f : files) {
copyFiles(f, targetFolder);
}
}
private static void copyFiles(File f, File targetFolder) throws IOException {
// System.out.println(targetFolder + "\\" + f.getName());
//读取源文件
FileInputStream in = new FileInputStream(f);
FileOutputStream out = null;
if (f.getName().endsWith(".jpg")) {
String newName = f.getName().substring(0, f.getName().lastIndexOf("."));
out = new FileOutputStream(targetFolder + "\\" + newName + ".png");
} else {
out = new FileOutputStream(targetFolder + "\\" + f.getName());
}
byte[] bytes = new byte[1024 * 8];
int len = 0;
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
out.flush();
}
in.close();
out.close();
(7)键盘录入学生信息按照总分排序并写入文本文件
需求:键盘录入3个学生信息(姓名,语文成绩(chineseScore),数学成绩(mathScore),英语成绩(englishScore)),
按照总分从高到低存入文本文件
分析:
a: 创建一个学生类: 姓名,语文成绩(chineseScore),数学成绩(mathScore),英语成绩(englishScore)
b: 因为要排序,所以需要选择TreeSet进行存储学生对象
c: 键盘录入学生信息,把学生信息封装成一个学生对象,在把学生对象添加到集合中
d: 创建一个高效的字符输出流对象
e: 遍历集合,把学生的信息写入到指定的文本文件中
f: 释放资源
测试类:
TreeSet<Student> set = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = s1.getTotalScore() - s2.getTotalScore();
int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
return -num2;
}
});
for (int i = 1; i <= 3; i++) {
Student student = new Student();
Scanner sc = new Scanner(System.in);
System.out.println("请输入第" + i + "个学生的姓名");
String name = sc.nextLine();
student.setName(name);
System.out.println("请输入第" + i + "个学生的语文成绩");
int yw = sc.nextInt();
student.setChineseScore(yw);
System.out.println("请输入第" + i + "个学生的数学成绩");
int xx = sc.nextInt();
student.setMathScore(xx);
System.out.println("请输入第" + i + "个学生的英语成绩");
int yy = sc.nextInt();
student.setEnglishScore(yy);
//将三个学习放到集合中,并按照总分排序
set.add(student);
}
//遍历集合将学生的考试信息,保存到文本文件中
BufferedWriter writer = new BufferedWriter(new FileWriter(System.currentTimeMillis()+"studentScore.txt"));
//先输出表头
writer.write("学生序号" + "\t" + "学生姓名" + "\t" + "语文成绩" + "\t" + "数学成绩" + "\t" + "英语成绩" + "\t" + "总分");
writer.newLine();
writer.flush();
int index = 1;
for (Student student : set) {
writer.write(index + "\t" + student.getName() + "\t" + student.getChineseScore() + "\t" + student.getMathScore() + "\t" + student.getEnglishScore() + "\t" + student.getTotalScore());
index++;
writer.newLine();
writer.flush();
}
writer.close();