Java文件类操作实例总结

来源:互联网 发布:淘宝店铺店招图片尺寸 编辑:程序博客网 时间:2024/03/02 15:11

1.1    文件类操作

1.1.1  递归文件删除

 

         public static void main(String[] args) {

                   File dir = newFile("E:\\homeFile");

                   DeleteDirAndFile(dir);

         }

 

         /***

          * 删除指定的文件夹(包含内容)

          * @param dir  指定的文件

          */

         private static voidDeleteDirAndFile(File dir) {

                   //写代码需要保证代码的健壮性

                   //入参检测

                   if(dir==null ||!dir.isDirectory()){

                            //如果参数报错,通常会抛出非法参数异常

                            throw newIllegalArgumentException("File对象不能为空,并且只能是文件夹");

                   }

                   //删除文件中的所有内容

                   //如果File对象描述的是文件,调用listFiles方法返回的是null

                   File[] files=dir.listFiles();

                   for (File f : files) {

                            if(f.isFile()){

                                     //如果是文件,就直接删除

                                     f.delete();

                            }else{

                                     //如果是文件夹,就需要先删除文件夹中的内容,再删除文件夹

                                     DeleteDirAndFile(f);       //递归调用

                            }

                   }

                   //删除文件本身(空文件夹)

                   dir.delete();

         }

 

1.1.2  文件及文件内容拷贝与新异常处理机制

/***

 * 将一个文件夹(包含子目录)的内容复制到其它目录中。提示:通过字节流和递归进行复制

 *

 */

public classCopyDirAndFile {

 

         public static void main(String[] args){

                   File srcDir = newFile("E:\\homeTest");

                   File desDir = newFile("E:\\homeTest_copy");

                   CopyDir(srcDir, desDir);

         }

 

         /***

          * 文件夹拷贝

          *

          * @param srcDir

          *           被拷贝的文件夹

          * @param desDir

          *           文件夹拷贝到的目标位置

          */

         private static void CopyDir(FilesrcDir, File desDir) {

                   if (srcDir == null ||!srcDir.isDirectory()) {

                            throw newIllegalArgumentException("被复制的必须是一个文件夹并且不能为空");

                   }

                   if (!desDir.exists()) {

                            // 创建空文件夹

                            desDir.mkdir();

                   }

 

                   File[] files =srcDir.listFiles();

                  for(File f : files) {

                            if (f.isFile()) {

                                     // 拷贝文件

                                     copyFile(f,new File(desDir, f.getName()));

                            } else if(f.isDirectory()) {

                                     // 拷贝文件

                                     CopyDir(f,new File(desDir, f.getName()));

                            }

                   }

         }

 

         /****

          * 文件的拷贝

          *

          * @param src

          *           被拷贝的文件

          * @param des

          *           文件拷贝到的目标位置

          */

         private static void copyFile(File src,File des) {

                   if (src == null ||!src.isFile()) {

                            throw newIllegalArgumentException("被复制的必须是一个文件并且不能为空");

                   }

                  /*

                    * JDK1.7新特性,自动释放资源(try-with-resource语法糖

                    * 1try后的圆括号中写上创建资源的代码,并且在这里面被创建的资源会进行自动释放(先开启后释放)

                    * 2)可以写入多个资源,多个资源之间用";"进行分割 3)资源类型必须是实现了AutoCloseable接口

                    * 4)在try后面的括号中创建的资源自动加上了final修饰

                    */

                   try (FileInputStream fis = newFileInputStream(src);

                                     FileOutputStream fos = newFileOutputStream(des)) {

                            byte[] bur = newbyte[1024];

                            int len = 0;

                            while ((len =fis.read(bur)) != -1) {

                                     fos.write(bur,0, len);

                            }

 

                   } catch (Exception e) {

                            e.printStackTrace();

                   }

         }

}

 

1.1.3  缓冲流结合实际综合运用

程序要求【

/*如在E盘下有一个Test.txt文本文件内容是

 #刘德华#89#77#60

 #张信哲#76#97#70

 #周杰伦#89#88#90

 #随便啦#87#70#80

 要求通过java读取文本并把文本中的每一行后面的三个成绩相加,

 最后按从大到小的顺序输出到另一个文本文件中.

 输出后的文本文件内容应为:

 #周杰伦#267

 #张信哲#243

 #随便啦#237

 #刘德华#226

 PS:尽量把此题做成一个模块性质的东西,并不是单独当成一道题做!*/

程序源码:

publicclass Record {

         private String name;

         private int num1,num2,num3;

         private int sum;

        

         public Record(){

                  

         }

 

         public Record(String name, int num1,int num2, int num3) {

                   this.name = name;

                   this.num1 = num1;

                   this.num2 = num2;

                   this.num3 = num3;

                   this.sum =num1+num2+num3;

         }

 

         public String getName() {

                   return name;

         }

 

         public void setName(String name) {

                   this.name = name;

         }

 

         public int getNum1() {

                   return num1;

         }

 

         public void setNum1(int num1) {

                   this.num1 = num1;

         }

 

         public int getNum2() {

                   return num2;

         }

 

         public void setNum2(int num2) {

                   this.num2 = num2;

         }

 

         public int getNum3() {

                   return num3;

         }

 

         public void setNum3(int num3) {

                   this.num3 = num3;

         }

 

         public int getSum() {

                   return sum;

         }

 

         public void setSum(int sum) {

                   this.sum = sum;

         }

 

         @Override

         public String toString() {

                   return "Record[name=" + name + ", num1=" + num1 + ", num2=" + num2

                                     + ",num3=" + num3 + ", sum=" + sum + "]";

         }

        

         public String getData(){

                   StringBuffer sb = newStringBuffer();

                   sb.append("#").append(name).append("#").append(sum);

                   return sb.toString();

         }

}                                      以上实体类

publicclass Demo {

 

         public static void main(String[] args){

                   // 读数据

                   List<Record> list =readData();

                  

                   //将list中的求和数值按降序排列

                   Collections.sort(list, new Comparator<Record>(){

                            @Override

                            public intcompare(Record o1, Record o2) {

                                     returno2.getSum() - o1.getSum();

                            }

                   });

                  

                   for (Record record : list) {

//                        System.out.println(record);

                            System.out.println(record.getData());

                   }

                  

                   //将list集合中的数据写入到另一个文件中去

                   writeData(list);

         }

 

         private static voidwriteData(List<Record> list) {

                   BufferedWriter bw = null;

                   try {

                             bw = new BufferedWriter(newFileWriter("buffer_ex_des.txt"));

                             for (Record record : list) {

                                     bw.write(record.getData());

                                     bw.newLine();

                                     bw.flush();      //如果数据不是很多,该行可以省略,如果数据比较多,那就要每写一次就刷新一次

                            }

                   } catch (IOException e) {

                            e.printStackTrace();

                   }finally{

                            if(bw != null){

                                     try {

                                               bw.close();

                                               bw= null;

                                     } catch(IOException e) {

                                               e.printStackTrace();

                                     }

                            }

                   }

         }

 

         private static List<Record>readData() {

                   List<Record> list = newArrayList<Record>();

                   BufferedReader br = null;

                   try {

                            br = newBufferedReader(new FileReader("buffer_ex_src.txt"));

                            String line = null;

                            while ((line =br.readLine()) != null) {

                                     String[]strs = line.split("#");

                                     String name= strs[1];

                                     int num1 =Integer.parseInt(strs[2]);

                                     int num2 =Integer.parseInt(strs[3]);

                                     int num3 =Integer.parseInt(strs[4]);

                                     list.add(newRecord(name, num1, num2, num3));

                            }

                            return list;

                   } catch (IOException e) {

                            // TODOAuto-generated catch block

                            e.printStackTrace();

                   } finally {

                            if (br != null) {

                                     try {

                                               br.close();

                                               br= null;

                                     } catch(IOException e) {

                                               //TODO Auto-generated catch block

                                               e.printStackTrace();

                                     }

                            }

                   }

                   return null;

         }

 

}

 

1.1.4  文件过滤综合运用

/***

 *

 *输出一个文件夹(包括子目录)中的所有以".java"结尾的文件的文件名

 *扩展需求:

 *1、将所有.java文件的文件路径都存入集合中

 *2、将规律的规则抽取出来,方法的调用者可以自定义过滤的规则

 *

 *开闭原则:对修改封闭,对扩展开放

 *

 */

publicclass FileFilterT {

 

         public static void main(String[] args){

                  

                   File dir = newFile("E:\\homeTest");

                   List<String> list = newArrayList<String>();

                   //方式一

//               traverse(dir,list);

                   //方式二

//               traverse2(dir,list,newMyFilter());

                   //方式三

                   // 方式三

                   traverse3(dir, list, newFileFilter() {

                            @Override

                            public booleanaccept(File file) {

                                     returnfile.getName().endsWith(".class") || file.isDirectory();

                            }

                   });

                   //循环遍历list集合

                   for (String str : list) {

                            System.out.println(str);

                   }

         }

 

         public static void traverse3(File dir,List<String> list, FileFilter filter) {

                   if(dir == null ||!dir.isDirectory()) {

                            throw newIllegalArgumentException("File不能为空并且必须是一个文件夹");

                   }

                   File[] files =dir.listFiles(filter);

                   for (File f : files) {

                            if(f.isFile()) {

                                     list.add(f.getName());

                            } else {

                                     traverse3(f,list, filter);

                            }

                   }

         }

 

         private static void traverse2(File dir,List<String> list, MyFilter fitler) {

                   if(dir == null ||!dir.isDirectory() ){

                            throw new IllegalArgumentException("File不能为空并且必须是一个文件夹");

                   }

                   File[] files =dir.listFiles();

                   for (File f : files) {

                            if(f.isFile()&& fitler.accept(f)){

                                     list.add(f.getName());

                            }elseif(f.isDirectory()){

                                     traverse2(f,list, fitler);

                            }

                   }

         }

 

         private static void traverse(File dir,List<String> list) {

                   if(dir == null ||!dir.isDirectory()){

                            //抛出非法参数异常

                            throw newIllegalArgumentException("File不能为空并且必须是一个文件夹");

                   }

                   File[] files =dir.listFiles();

                   for (File f : files) {

                            if(f.isFile() &&f.getName().endsWith(".java")){

                                     list.add(f.getName());

                            }elseif(f.isDirectory()){

                                     traverse(f,list);

                            }

                   }

         }

}

 

interfaceIMyFilter{

         //过滤指定的文件

         public abstract boolean accept(Filefile);

}

 

classMyFilter implements IMyFilter{

 

         @Override

         public boolean accept(File file) {

                   returnfile.getName().endsWith(".java");

         }

        

}

获取一个文件夹下所有指定后缀名(.java)的文件(包括子文件夹中的内容),并将这些文件的绝对路径写入到一个文本文件中

 

publicclass Ex3 {

 

         public static void main(String[] args)throws IOException {

                   File dir = newFile("E:\\homeTest");

                   List<File> list = newArrayList<File>();

                   traverse(dir, list);

                   BufferedWriter bw = newBufferedWriter(new FileWriter("buffer_ex3.txt"));

                   for (File file : list) {

//                        System.out.println(file.getAbsolutePath());

                            bw.write(file.getAbsolutePath());

                            bw.newLine();

                            bw.flush();

                   }

                   bw.close();

         }

 

         /**

          * 遍历文件夹,获取指定后缀名的对象

          * @param dir 文件目录

          * @param list list集合

          */

         public static void traverse(File dir,List<File> list){

                   if(dir == null ||!dir.exists() || !dir.isDirectory()){

                            throw newIllegalArgumentException("必须是一个存在的文件夹,并且文件夹不能为空!");

                   }

                   File[] files =dir.listFiles();

                   for (File f : files) {

                            if(f.isFile()&& f.getName().endsWith(".java")){

                                     list.add(f);

                            }elseif(f.isDirectory()){

                                     traverse(f,list);

                            }

                   }

         }

}

 

1.1.5  文件操作与对象结合综合实例

/*

#姓名 性别 帐号 发生额

刘德华|1|4155990188888888|300.00

晓龙|1|1155990199999999|500.00

黄晓明|1|4155990100000000|1000.50

张东健|1|4155990155555555|600.99

梁朝伟|0|4155990111111111|5000.00

刘德华|1|4155990188888888|200.00

张东健|1|4155990155555555|500.99

刘德华|1|4155990188888888|1200.00 * 实现功能:

 * 一个人可能消费有多笔。(当姓名和账号相同的话就认为是同一人)统计每个人的消费总额,

 * 按消费额升序排序。要求显示每个人的姓名、性别、帐号、消费总额的信息

 */

public class Ex2 {

 

         publicstatic void main(String[] args) {

                   List<TransRecord>list = readData();

                   Collections.sort(list);

                   for(TransRecord record : list) {

                            System.out.println(record);

                   }

         }

 

         privatestatic List<TransRecord> readData() {

                   BufferedReaderbr = null;

                   try{

                            List<TransRecord>list = new ArrayList<TransRecord>();

                            br= new BufferedReader(new FileReader("buffer_ex2.txt"));

                            Stringline = null;

                            while((line= br.readLine()) != null) {

                                     if(line.startsWith("#")){

                                               continue;

                                     }

                                     String[]strs = line.split("\\|");

                                     Stringname = strs[0];

                                     intgender = Integer.parseInt(strs[1]);

                                     Stringaccount = strs[2];

                                     doublemoney = Double.parseDouble(strs[3]);

                                     //TransRecord record = new TransRecord(name, gender, account, money);

                                     //遍历集合中的每一个元素,判断集合中有没有指定的用户的记录

                                     booleanflag = false; // 代表有没有现有的记录

                                     for(TransRecord record : list) {

                                               if(record.getName().equals(name)&& record.getAccount().equals(account)) {

                                                        //record.setMoney(record.getMoney() + money);

                                                        record.addMoney(money);

                                                        flag= true;

                                               }

                                     }

                                     if(!flag){

                                               list.add(newTransRecord(name, gender, account, money));

                                     }

                            }

                            returnlist;

                   }catch (IOException e) {

                            e.printStackTrace();

                   }finally {

                            if(br!= null) {

                                     try{

                                               br.close();

                                               br= null;

                                     }catch (IOException e) {

                                               e.printStackTrace();

                                     }

                            }

                   }

                   returnnull;

         }

 

}

 

class TransRecord implementsComparable<TransRecord> {

        

         privateString name;

         privateint gender;

         privateString account;

         privatedouble money;

 

         publicTransRecord() {

         }

 

         publicTransRecord(String name, int gender, String account, double money) {

                   this.name= name;

                   this.gender= gender;

                   this.account= account;

                   this.money= money;

         }

 

         publicString getName() {

                   returnname;

         }

 

         publicvoid setName(String name) {

                   this.name= name;

         }

 

         publicint getGender() {

                   returngender;

         }

 

         publicvoid setGender(int gender) {

                   this.gender= gender;

         }

 

         publicString getAccount() {

                   returnaccount;

         }

 

         publicvoid setAccount(String account) {

                   this.account= account;

         }

 

         publicdouble getMoney() {

                   returnmoney;

         }

 

         publicvoid setMoney(double money) {

                   this.money= money;

         }

        

         publicvoid addMoney(double money){

                   this.money+= money;

         }

 

         @Override

         publicString toString() {

                   return"TransRecord [name=" + name + ", gender=" + gender

                                     +", account=" + account + ", money=" + money +"]";

         }

 

         @Override

         publicint compareTo(TransRecord o) {

                   if(this.money> o.money) {

                            return1;

                   }else if(this.money < o.money) {

                            return-1;

                   }else {

                            return0;

                   }

         }

 

}

4 0
原创粉丝点击