IO流小结、练习案例(点名器、对象到集合再到文件、文件到集合改进版、集合到文件数据排序改进版、复制单级文件夹复制多级文件夹)、字节流字符流复制异常处理(try..catch…)JDK7优化版本异常处理

IO流小结

练习案例

点名器

思路:

  1. 创建字符缓冲输入流
  2. 创建ArrayList集合对象
  3. 调用字符缓冲输入流对象的方法读数据
  4. 把读到的字符串数据存储到集合中
  5. 释放资源
  6. 用Random类产生一个随机数,随机数的范围再:[0,集合长度)
  7. 把第6步产生的随机数作为索引到ArrayList集合中获取值
  8. 把第7步得到的数据输出在控制台

代码示例:

ArrayList<String> demo = new ArrayList<String>();

BufferedReader bfr = new BufferedReader(newFileReader("C:\\Users\\23353\\Desktop\\JAVA笔记\\java笔记.txt"));
String str;
while( (str = bfr.readLine()) != null ){
   
	demo.add(str);
}
Random r = new Random();
int temp = r.nextInt(demo.size());
System.out.println(demo.get(temp));

bfr.close();

对象到集合再到文件

案例:先将学生对象存入ArrayList再用字符缓冲流将学生对象写入文件中
代码示例:

ArrayList<Student> demo = new ArrayList<Student>();          
//创建集合

BufferedWriter bfw = new BufferedWriter(newFileWriter("C:\\Users\\23353\\Desktop\\JAVA笔记\\测试案例.txt"));   
//创建目标文件

Student s1 = new Student("张三",1,89);       //创建学生对象
Student s2 = new Student("李四",2,79);
Student s3 = new Student("王五",3,97);
demo.add(s1);                 //将学生对象存入集合
demo.add(s2);
demo.add(s3);

for(Student s:demo){
              
//增强for循环遍历集合,并将集合中的对象写入字符缓冲流中
	StringBuilder str = new StringBuilder();           
//注意:每次循环需要重新创建新的StringBuilder字符串,否则append会将所有的字符串连接在一起
	str.append(s.getName()).append(",").append(s.getId()).append(",").append(s.getScore());       
//用StirngBuilder将字符串拼接起来
	bfw.write(str.toString());
	bfw.newLine();       //换行
	bfw.flush();
}
bfw.close();      //释放资源

文件到集合改进版

案例:把文本文件中的数据读取到集合中,并遍历集合。
要求:文件中每一行数据是一个学生对象的成员变量值
举例:test_001,张三,18,北京
代码示例:

ArrayList<Student> demo = new ArrayList<Student>();

BufferedReader bfr = new BufferedReader(new FileReader("C:\\Users\\23353\\Desktop\\JAVA笔记\\测试案例.txt"));

String ch;
while((ch = bfr.readLine())!=null){
   
	String[] str = ch.split(",");  
	//将字符串用“,”分割并复制给字符串数组
	Student s = new Student();                
	//每次循环创建新的学生对象
	s.setName(str[0]);
	s.setId(Integer.parseInt(str[1]));         
	//调用int Integer.parseInt(String s);方法将String转换为Int
	s.setScore(Integer.parseInt(str[2]));
	demo.add(s);
}
for(Student s:demo){
   
	System.out.println(s.getName()+","+s.getId()+","+s.getScore());
}
bfr.close();          //释放资源

集合到文件数据排序改进版

案例:键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩)。要求按照成绩总分从高到低写入文本文件
格式:姓名,语文成绩,数学成绩,英语成绩
代码示例:

 //创建Set集合
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>(){
          
@Override                                                                                        
//用内部类重写Comparator比较器中的compare方法
public int compare(Student s1,Student s2){
   
	int nums = s2.getScore()-s1.getScore();
	int num = nums==0?s2.getName().compareTo(s1.getName()):nums;
	return num;
	}
});
BufferedWriter bfw = new BufferedWriter(new FileWriter("C:\\Users\\23353\\Desktop\\JAVA笔记\\测试案例.txt"));    
//定义字符缓冲流

for(int i=0;i<5;i++){
        //循环输入5次,录入学生信息
	Scanner sc = new Scanner(System.in);
	Student s = new Student();
	
	System.out.println("输入学生信息");
	
	String name=sc.nextLine();
	int id=sc.nextInt();
	int score=sc.nextInt();
	
	s.setName(name);
	s.setId(id);
	s.setScore(score);
	ts.add(s);
}

for(Student s:ts){
          //遍历Set集合,将Set集合内容拼接成字符串写入文件中
	StringBuilder str = new StringBuilder();
	str.append(s.getName()).append(",").append(s.getId()).append(",").append(s.getScore());
	System.out.println(str.toString());
	bfw.write(str.toString());
	bfw.newLine();
	bfw.flush();
}
	
bfw.close();                //释放资源

复制单级文件夹

需求:把"源文件"这个文件夹复制到模块目录下
代码示例:

public static void main(String[] args) throws IOException{
   
	File Folder = new File("源文件");                 //创建数据源目录File对象
	String Foldername = Folder.getName();                    //得到数据源目录名称
	File Dest = new File("目的地文件",Foldername);   //创建目的地File对象
	if(!(Dest.exists())){
             //判断目的地目录下对应的File是否存在,不存在时创建
		Dest.mkdir();
	}
	File[] listFiles = Folder.listFiles();       //用File数组接收数据源目录下的 所有文件
	for(File file : listFiles){
                  //遍历接收所有文件的File数组
		String Filename = file.getName();         //获取源文件的File名称
		File dest = new File(Dest,Filename);     //创建目的地文件File对象
		copyfile(file,dest);              //进入复制文件方法 
		}
}

private static void copyfile(File file,File dest) throws IOException{
         //字节缓冲流复制File文件
	BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest));
	BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
	byte[] by = new byte[1024];
	int len;
	while((len=in.read(by))!=-1){
   
		out.write(by,0,len);
	}
	out.close();
	in.close();
}

复制多级文件夹(递归调用)

注意:复制文件必须要在数据源和目的地都存在相同名称的File对象时才可以进行复制转换
代码示例:

public static void main(String[] args) throws IOException{
   
	File Folder = new File("D:\\java000\\test001");        //数据源
	File destName = new File("D:\\test0001");                   //目的地
	copyAll(Folder,destName);

}
private static void copyAll(File file,File dest) throws IOException{
   
	if(file.isDirectory()){
   
		String name = file.getName();
		File xinFolder = new File(dest,name);          //D:\test0001\test001
		if(!xinFolder.exists()){
   
			xinFolder.mkdirs();
		}
		File[] listFiles = file.listFiles();
		for(File list:listFiles){
   
			copyAll(list,xinFolder);          //进入递归
		}
	}else{
   
		File newfile = new File(dest,file.getName());       
		copy(file,newfile);
	}
}
private static void copy(File file,File newfile) throws IOException{
   
	BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newfile));
	BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
	byte[] by = new byte[1024];
	int len;
	while((len=in.read(by))!=-1){
   
		out.write(by,0,len);
	}
	out.close();
	in.close();
}

字节流字符流复制异常处理(try…catch…)JDK7优化版本异常处理

代码示例:

JDK7以后版本(简便常用版)
代码:
try(BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newfile));BufferedInputStream in=new BufferedInputStream(new FileInputStream(file))){
        
//括号内用分号隔开
	byte[] by = new byte[1024];
	int len;
	while((len=in.read(by))!=-1){
   
		out.write(by,0,len);
	}
}catch(IOException e){
   
	e.printStackTrace();
}
-------------------------------------------------------------------------------------------------------------------------
//try..catch..finally方法(字节流复制文件异常处理)
BufferedOutputStream out = null;
BufferedInputStream in = null;
try{
   
	out=new BufferedOutputStream(new FileOutputStream(newfile));
	in=new BufferedInputStream(new FileInputStream(file));
	byte[]by=new byte[1024];
	int len;
	while((len=in.read(by))!=-1){
   
	out.write(by,0,len);
	}
}catch(IOException e){
   
	e.printStackTrace();
}finally{
   
	if(out!=null){
   
		try{
   
			out.close();
		}catch(IOException a){
   
			a.printStackTrace();
		}
	}
	if(in!=null){
   
		try{
   
			in.close();
		}catch(IOException e){
   
			e.printStackTrace();
		}
	}
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务