21、 IO流小结
IO流练习
1、集合到文件案例
//案例一:把ArrayList集合中的字符串数据写入文本文件
//要求:每一个字符串元素作为文件中的一行数据
public class ArrayListToTxtDemo1 {
public static void main(String[] args) throws IOException {
ArrayList
arr.add("hello");
arr.add("world");
arr.add("beijing");
BufferedWriter bw = new BufferedWriter(new FileWriter("f:\test\abc.txt"));
for(String s: arr){
bw.write(s);
bw.newLine();
bw.flush();
}
bw.close();
}
}
2、文件到集合案例
//案例二:文件到集合
public class TxtToArrayListDemo2 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("f:\test\abc.txt"));
ArrayList
String line;
while((line=br.readLine())!=null){
arr.add(line);
}
br.close();
for(String s: arr){
System.out.println(s);
}
}
}
3、 随机点名案例
//案例三:随机点名
public class CallNameDemo3 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("f:\test\abc.txt"));
ArrayList
String line;
while((line=br.readLine())!=null){
arr.add(line);
}
br.close();
Random r = new Random();
int index = r.nextInt(arr.size());
String name = arr.get(index);
System.out.println("随机点名的同学是:"+name);
}
}
4、集合到文件案例(改进版)
//集合到文件案例(改进版)
//需求:把ArrayList集合中的学生数据写入到文本文件,要求:每一个学生对象的数据作为文件中一行数据
//输出结果格式:学号,姓名,年龄,地址 如:itheima001,张三,24,北京海淀区
public class ArrayListToTxtDemo4 {
public static void main(String[] args) throws IOException {
ArrayList
Student stu1 = new Student("张三",24,"itheima001","北京海淀区");
Student stu2 = new Student("张四",25,"itheima002","杭州西湖区");
Student stu3 = new Student("张五",26,"itheima003","深圳罗湖区");
Student stu4 = new Student("张六",27,"itheima004","武汉高新区");
Student stu5 = new Student("张七",28,"itheima005","郑州新郑区");
Student stu6 = new Student("张八",29,"itheima006","成都双流区");
arr.add(stu1);
arr.add(stu2);
arr.add(stu3);
arr.add(stu4);
arr.add(stu5);
arr.add(stu6);
BufferedWriter bw = new BufferedWriter(new FileWriter("f:\test\bcd.txt"));
for(Student s: arr){
StringBuilder sb = new StringBuilder();
sb.append(s.getSid()).append(",").append(s.getName()).append(",").append(s.getAge()).append(",").append(s.getAddress());
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
bw.close();
}
}
4、 文件到集合案例(改进版)
//文件到集合案例(改进版)
//需求:把文本文件的数据读取到集合中,并遍历集合
//要求:文件中每一行数据是一个学生对象的成员变量值
public class TxtToArrayListDemo5 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("f:\test\bcd.txt"));
ArrayList
String line;
while((line=br.readLine())!=null){
String[] stuArray = line.split(",");
Student stu = new Student();
stu.setSid(stuArray[0]);
stu.setName(stuArray[1]);
stu.setAge(Integer.parseInt(stuArray[2]));
stu.setAddress(stuArray[3]);
arr.add(stu);
}
br.close();
for(Student s:arr){
System.out.println(s.getSid()+","+s.getName()+","+s.getAge()+","+s.getAddress());
}
}
}
5、 集合到文件案例(数据排序改进版)
//案例:集合到文件(数据排序改进版)
//需求:键盘录入5个学生信息(格式:姓名,语文成绩,数学成绩,英语成绩),要求按照成绩总分从高到低写入文本文件
//举例:王五,96,98,99
public class ArrayListToTxtDemo6 {
public static void main(String[] args) throws IOException {
TreeSet
@Override
public int compare(Student2 s1, Student2 s2) {
//成绩总分从高到低
int num = s2.getSum()-s1.getSum();
//次要条件
int num2 = num==0?s1.getChinese()-s2.getChinese():num;
int num3 = num2==0?s1.getMath()-s2.getMath():num2;
int num4 = num3==0?s1.getName().compareTo(s2.getName()):num3;
return num4;
}
});
//键盘录入学生成绩
for(int i=0;i<5;i++){
Scanner sc = new Scanner(System.in);
System.out.println("请录入第"+(i+1)+"学习信息:");
System.out.println("姓名:");
String name = sc.nextLine();
System.out.println("语文成绩:");
int chinese = sc.nextInt();
System.out.println("数学成绩:");
int math = sc.nextInt();
System.out.println("英语成绩:");
int english = sc.nextInt();
//创建学生对象
Student2 s = new Student2();
s.setName(name);
s.setChinese(chinese);
s.setEnglish(english);
s.setMath(math);
//把学生对象添加到集合中
ts.add(s);
}
//创建字符缓冲输出流对象
BufferedWriter bw = new BufferedWriter(new FileWriter("f:\test\ts.txt"));
//遍历集合,得到每一个学生对象
for(Student2 s: ts){
//把学生对象的数据拼接成指定格式的字符串
StringBuilder sb = new StringBuilder();
sb.append(s.getName()).append(",").append(s.getChinese()).append(",").append(s.getEnglish()).append(",").append(s.getMath()).append(",").append(s.getSum());
//调用字符缓冲输出流对象的方法写数据
bw.write(sb.toString());
bw.newLine();
bw.flush();
}
bw.close();
}
}
6、复制单级文件夹
注:单级文件夹就是文件夹里面只有文件,没有文件夹
//案例:复制单级文件夹
//需求:把F:\itcast这个文件夹复制到模块目录下
public class CopyFolderDemo7 {
public static void main(String[] args) throws IOException {
//1、创建数据源File对象,路径是F:\itcast
File srcFolder = new File("F:\itcast");
//2、获取数据源目录File对象的名称(itcast)
String srcFolderName = srcFolder.getName();
//3、创建目的地目录File对象,路径名是模块名+itcast组成(E:\itcast)
File destFolder = new File("E:",srcFolderName);
//4、判断目的地目录对应的File是否存在,如果不存在,就创建
if(!destFolder.exists()){
destFolder.mkdir();
}
//5、获取数据源目录下所有文件的File数组
File[] listFiles = srcFolder.listFiles();
//6、遍历File数组,得到每一个File对象,其实就是数据源文件
for(File srcFile:listFiles){
//7、比如:数据源文件:E:itcast\1.jpg
// 获取数据源文件File对象的名称(1.jpg)
String srcFileName = srcFile.getName();
//8、创建目的地文件File对象,路径名是目的地目录+1.jpg组成(E:\itcast\1.jpg)
File destFile = new File(destFolder,srcFileName);
// 9、复制文件:由于文件不仅仅是文本文件,还有图片、视频等文件,所以采用字节流复制文件
copyFile(srcFile,destFile);
}
}
//copy方法
private static void copyFile(File srcFile, File destFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new BufferedInputStream(new FileInputStream(srcFile)));
BufferedOutputStream bos = new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(destFile)));
byte[] bys = new byte[1024];
int len;
while((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
}
bos.close();
bis.close();
}
}
7、复制多级文件夹
public class CopyFolderDemo8 {
public static void main(String[] args) throws IOException {
//1、创建数据源File对象,路径是F:\test
File srcFile = new File("F:\test");
//2、创建目的地File对象,路径是E:\
File destFile = new File("E:\");
//写方法实现文件夹复制,参数为数据源File对象和目的地File对象
copyFolder(srcFile,destFile);
}
//复制文件夹的方法
private static void copyFolder(File srcFile, File destFile) throws IOException {
//4、判断数据源File是否是目录
if(srcFile.isDirectory()){
// A、在目的地下创建和数据源File名称一样的目录
String srcFileName = srcFile.getName();
File newFolder = new File(destFile,srcFileName);
if(!newFolder.exists()){
newFolder.mkdir();
}
//B、获取数据源File下索引文件或者目录的File数组
File[] fileArray = srcFile.listFiles();
//C、遍历该File数组,得到每一个File对象
for(File file: fileArray){
//D、把该File作为数据源File对象,递归调用复制文件夹的方法
copyFolder(file,newFolder);
}
}else{
//如果不是:说明就是文件,直接复制文件,用字节流
File newFile = new File(destFile,srcFile.getName());
copyFile(srcFile,newFile);
}
}
//copy方法
private static void copyFile(File srcFile, File destFile) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new BufferedInputStream(new FileInputStream(srcFile)));
BufferedOutputStream bos = new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(destFile)));
byte[] bys = new byte[1024];
int len;
while((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
}
bos.close();
bis.close();
}
}
8、 IO复制文件的异常处理三种方式
//复制文件的异常处理
//推荐使用JDK7方式
public class trycatchDemo9 {
public static void main(String[] args) {
}
//第三种:JDK9的改进方案
private static void method3()throws IOException{
FileReader fr = new FileReader("F:\test");
FileWriter fw = new FileWriter("E:\test");
try(fr;fw){
char[] chs = new char[1024];
int len;
while((len=fr.read())!=-1){
fw.write(chs,0,len);
}
}catch(IOException e){
e.printStackTrace();
}
}
//第二种:JDK7的改进方案
private static void method2(){
try( FileReader fr = new FileReader("F:\test");
FileWriter fw = new FileWriter("E:\test");){
char[] chs = new char[1024];
int len;
while((len=fr.read())!=-1){
fw.write(chs,0,len);
}
}catch(IOException e){
e.printStackTrace();
}
}
//第一种:try...catch...finally方式
private static void method1(){
FileWriter fw = null;
FileReader fr = null;
try {
fw = new FileWriter("F:\test");
fr = new FileReader("E:\test");
char[] chs = new char[1024];
int len;
while ((len = fr.read()) != -1) {
fw.write(chs, 0, len);
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(fw!=null){
try {
fw.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(fr!=null){
try {
fr.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
}



