Java笔记(19):IO流(01)

1、try...catch的方式处理异常1

 1 package cn.itcast_02;
 2 
 3 /*
 4  * 异常:程序出现了不正常的情况。
 5  * 
 6  * 程序的异常:Throwable
 7  *         严重问题:Error 我们不处理。这种问题一般都是很严重的,比如说内存溢出。
 8  *         问题:Exception
 9  *             编译期问题:不是RuntimeException的异常 必须进行处理的,因为你不处理,编译就不能通过。
10  *             运行期问题:RuntimeException    这种问题我们也不处理,因为是你的问题,而且这个问题出现肯定是我们的代码不够严谨,需要修正代码的。
11  * 
12  * 如何程序出现了问题,我们没有做任何处理,最终jvm会做出默认的处理。
13  * 把异常的名称,原因及出现的问题等信息输出在控制台。
14  * 同时会结束程序。
15  * 
16  * 我们自己如何处理异常呢?
17  * A:try...catch...finally
18  * B:throws 抛出
19  * 
20  * try...catch...finally的处理格式:
21  *         try {
22  *             可能出现问题的代码;
23  *         }catch(异常名 变量) {
24  *             针对问题的处理;
25  *         }finally {
26  *             释放资源;
27  *         }
28  * 
29  * 变形格式:
30  *         try {
31  *             可能出现问题的代码;
32  *         }catch(异常名 变量) {
33  *             针对问题的处理;
34  *         }
35  * 
36  * 注意:
37  *         A:try里面的代码越少越好
38  *         B:catch里面必须有内容,哪怕是给出一个简单的提示
39  */
40 public class ExceptionDemo {
41     public static void main(String[] args) {
42         // 第一阶段
43         int a = 10;
44         // int b = 2;
45         int b = 0;
46 
47         try {
48             System.out.println(a / b);
49         } catch (ArithmeticException ae) {
50             System.out.println("除数不能为0");
51         }
52 
53         // 第二阶段
54         System.out.println("over");
55     }
56 }

2、try...catch的方式处理异常2

  1 package cn.itcast_02;
  2 
  3 /*
  4  * A:一个异常
  5  * B:二个异常的处理
  6  *         a:每一个写一个try...catch
  7  *         b:写一个try,多个catch
  8  *             try{
  9  *                 ...
 10  *             }catch(异常类名 变量名) {
 11  *                 ...
 12  *             }
 13  *             catch(异常类名 变量名) {
 14  *                 ...
 15  *             }
 16  *             ...
 17  * 
 18  *             注意事项:
 19  *                 1:能明确的尽量明确,不要用大的来处理。
 20  *                 2:平级关系的异常谁前谁后无所谓,如果出现了子父关系,父必须在后面。
 21  * 
 22  * 注意:
 23  *         一旦try里面出了问题,就会在这里把问题给抛出去,然后和catch里面的问题进行匹配,
 24  *         一旦有匹配的,就执行catch里面的处理,然后结束了try...catch
 25  *         继续执行后面的语句。
 26  */
 27 public class ExceptionDemo2 {
 28     public static void main(String[] args) {
 29         // method1();
 30 
 31         // method2();
 32 
 33         // method3();
 34 
 35         method4();
 36     }
 37 
 38     public static void method4() {
 39         int a = 10;
 40         int b = 0;
 41         int[] arr = { 1, 2, 3 };
 42 
 43         // 爷爷在最后
 44         try {
 45             System.out.println(a / b);
 46             System.out.println(arr[3]);
 47             System.out.println("这里出现了一个异常,你不太清楚是谁,该怎么办呢?");
 48         } catch (ArithmeticException e) {
 49             System.out.println("除数不能为0");
 50         } catch (ArrayIndexOutOfBoundsException e) {
 51             System.out.println("你访问了不该的访问的索引");
 52         } catch (Exception e) {
 53             System.out.println("出问题了");
 54         }
 55 
 56         // 爷爷在前面是不可以的
 57         // try {
 58         // System.out.println(a / b);
 59         // System.out.println(arr[3]);
 60         // System.out.println("这里出现了一个异常,你不太清楚是谁,该怎么办呢?");
 61         // } catch (Exception e) {
 62         // System.out.println("出问题了");
 63         // } catch (ArithmeticException e) {
 64         // System.out.println("除数不能为0");
 65         // } catch (ArrayIndexOutOfBoundsException e) {
 66         // System.out.println("你访问了不该的访问的索引");
 67         // }
 68 
 69         System.out.println("over");
 70     }
 71 
 72     // 两个异常的处理
 73     public static void method3() {
 74         int a = 10;
 75         int b = 0;
 76         int[] arr = { 1, 2, 3 };
 77 
 78         try {
 79             System.out.println(arr[3]);
 80             System.out.println(a / b);
 81             // System.out.println(arr[3]);
 82         } catch (ArithmeticException e) {
 83             System.out.println("除数不能为0");
 84         } catch (ArrayIndexOutOfBoundsException e) {
 85             System.out.println("你访问了不该的访问的索引");
 86         }
 87 
 88         System.out.println("over");
 89     }
 90 
 91     // 两个异常
 92     public static void method2() {
 93         int a = 10;
 94         int b = 0;
 95         try {
 96             System.out.println(a / b);
 97         } catch (ArithmeticException e) {
 98             System.out.println("除数不能为0");
 99         }
100 
101         int[] arr = { 1, 2, 3 };
102         try {
103             System.out.println(arr[3]);
104         } catch (ArrayIndexOutOfBoundsException e) {
105             System.out.println("你访问了不该的访问的索引");
106         }
107 
108         System.out.println("over");
109     }
110 
111     // 一个异常
112     public static void method1() {
113         // 第一阶段
114         int a = 10;
115         // int b = 2;
116         int b = 0;
117 
118         try {
119             System.out.println(a / b);
120         } catch (ArithmeticException ae) {
121             System.out.println("除数不能为0");
122         }
123 
124         // 第二阶段
125         System.out.println("over");
126     }
127 }

3、JDK7针对多个异常的处理方案

 1 package cn.itcast_02;
 2 
 3 /*
 4  * JDK7出现了一个新的异常处理方案:
 5  *         try{
 6  * 
 7  *         }catch(异常名1 | 异常名2 | ...  变量 ) {
 8  *             ...
 9  *         }
10  * 
11  *         注意:这个方法虽然简洁,但是也不够好。
12  *             A:处理方式是一致的。(实际开发中,好多时候可能就是针对同类型的问题,给出同一个处理)
13  *            B:多个异常间必须是平级关系。
14  */
15 public class ExceptionDemo3 {
16     public static void main(String[] args) {
17         method();
18     }
19 
20     public static void method() {
21         int a = 10;
22         int b = 0;
23         int[] arr = { 1, 2, 3 };
24 
25         // try {
26         // System.out.println(a / b);
27         // System.out.println(arr[3]);
28         // System.out.println("这里出现了一个异常,你不太清楚是谁,该怎么办呢?");
29         // } catch (ArithmeticException e) {
30         // System.out.println("除数不能为0");
31         // } catch (ArrayIndexOutOfBoundsException e) {
32         // System.out.println("你访问了不该的访问的索引");
33         // } catch (Exception e) {
34         // System.out.println("出问题了");
35         // }
36 
37         // JDK7的处理方案
38         try {
39             System.out.println(a / b);
40             System.out.println(arr[3]);
41         } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
42             System.out.println("出问题了");
43         }
44 
45         System.out.println("over");
46     }
47 
48 }

4、编译期异常和运行期异常的区别

 1 package cn.itcast_03;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 /*
 8  * 编译时异常和运行时异常的区别
 9  * 编译期异常:Java程序必须显示处理,否则程序就会发生错误,无法通过编译
10  * 运行期异常:无需显示处理,也可以和编译时异常一样处理
11  */
12 public class ExceptionDemo {
13     public static void main(String[] args) {
14         // int a = 10;
15         // int b = 0;
16         // if (b != 0) {
17         // System.out.println(a / b);
18         // }
19 
20         String s = "2014-11-20";
21         // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
22         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
23         // Date d = sdf.parse(s);
24         try {
25             Date d = sdf.parse(s);
26             System.out.println(d);
27         } catch (ParseException e) {
28             // e.printStackTrace();
29             System.out.println("解析日期出问题了");
30         }
31     }
32 }

5、Throwable的几个常见方法

 1 package cn.itcast_04;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 /*
 8  * 在try里面发现问题后,jvm会帮我们生成一个异常对象,然后把这个对象抛出,和catch里面的类进行匹配。
 9  * 如果该对象是某个类型的,就会执行该catch里面的处理信息。
10  * 
11  * 异常中要了解的几个方法:
12  * public String getMessage():异常的消息字符串        
13  * public String toString():返回异常的简单信息描述
14  *         此对象的类的 name(全路径名)
15  *         ": "(冒号和一个空格) 
16  *         调用此对象 getLocalizedMessage()方法的结果 (默认返回的是getMessage()的内容)
17  * printStackTrace() 获取异常类名和异常信息,以及异常出现在程序中的位置。返回值void。把信息输出在控制台。
18  */
19 public class ExceptionDemo {
20     public static void main(String[] args) {
21         String s = "2014-11-20";
22         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
23         try {
24             Date d = sdf.parse(s); // 创建了一个ParseException对象,然后抛出去,和catch里面进行匹配
25             System.out.println(d);
26         } catch (ParseException e) { // ParseException e = new ParseException();
27             // ParseException
28             // e.printStackTrace();
29 
30             // getMessage()
31             // System.out.println(e.getMessage());
32             // Unparseable date: "2014-11-20"
33 
34             // toString()
35             // System.out.println(e.toString());
36             // java.text.ParseException: Unparseable date: "2014-11-20"
37             
38             e.printStackTrace();
39             //跳转到某个指定的页面(index.html)
40         }
41         
42         System.out.println("over");
43     }
44 }

6、throws的方式处理异常

 1 package cn.itcast_05;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 /*
 8  * 有些时候,我们是可以对异常进行处理的,但是又有些时候,我们根本就没有权限去处理某个异常。
 9  * 或者说,我处理不了,我就不处理了。
10  * 为了解决出错问题,Java针对这种情况,就提供了另一种处理方案:抛出。
11  * 
12  * 格式:
13  *         throws 异常类名
14  *         注意:这个格式必须跟在方法的括号后面。
15  * 
16  * 注意:
17  *         尽量不要在main方法上抛出异常。
18  *         但是我讲课为了方便我就这样做了。
19  * 
20  * 小结:
21  *         编译期异常抛出,将来调用者必须处理。
22  *         运行期异常抛出,将来调用可以不用处理。
23  */
24 public class ExceptionDemo {
25     public static void main(String[] args) {
26         System.out.println("今天天气很好");
27         try {
28             method();
29         } catch (ParseException e) {
30             e.printStackTrace();
31         }
32         System.out.println("但是就是不该有雾霾");
33 
34         method2();
35     }
36 
37     // 运行期异常的抛出
38     public static void method2() throws ArithmeticException {
39         int a = 10;
40         int b = 0;
41         System.out.println(a / b);
42     }
43 
44     // 编译期异常的抛出
45     // 在方法声明上抛出,是为了告诉调用者,你注意了,我有问题。
46     public static void method() throws ParseException {
47         String s = "2014-11-20";
48         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
49         Date d = sdf.parse(s);
50         System.out.println(d);
51     }
52 }

7、throw的概述以及和throws的区别

 1 package cn.itcast_06;
 2 
 3 /*
 4  * throw:如果出现了异常情况,我们可以把该异常抛出,这个时候的抛出的应该是异常的对象。
 5  * 
 6  * throws和throw的区别(面试题)
 7     throws
 8         用在方法声明后面,跟的是异常类名
 9         可以跟多个异常类名,用逗号隔开
10         表示抛出异常,由该方法的调用者来处理
11         throws表示出现异常的一种可能性,并不一定会发生这些异常
12     throw
13         用在方法体内,跟的是异常对象名
14         只能抛出一个异常对象名
15         表示抛出异常,由方法体内的语句处理
16         throw则是抛出了异常,执行throw则一定抛出了某种异常
17  */
18 public class ExceptionDemo {
19     public static void main(String[] args) {
20         // method();
21         
22         try {
23             method2();
24         } catch (Exception e) {
25             e.printStackTrace();
26         }
27     }
28 
29     public static void method() {
30         int a = 10;
31         int b = 0;
32         if (b == 0) {
33             throw new ArithmeticException();
34         } else {
35             System.out.println(a / b);
36         }
37     }
38 
39     public static void method2() throws Exception {
40         int a = 10;
41         int b = 0;
42         if (b == 0) {
43             throw new Exception();
44         } else {
45             System.out.println(a / b);
46         }
47     }
48 }

8、finally关键字的特点及作用

 1 package cn.itcast_07;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 /*
 8  * finally:被finally控制的语句体一定会执行
 9  * 注意:如果在执行到finally之前jvm退出了,就不能执行了。
10  * 
11  * A:格式
12  *         try...catch...finally...
13  * B:用于释放资源,在IO流操作和数据库操作中会见到
14  */
15 public class FinallyDemo {
16     public static void main(String[] args) {
17         String s = "2014-11-20";
18         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
19 
20         Date d = null;
21         try {
22             // System.out.println(10 / 0);
23             d = sdf.parse(s);
24         } catch (ParseException e) {
25             e.printStackTrace();
26             System.exit(0);
27         } finally {
28             System.out.println("这里的代码是可以执行的");
29         }
30 
31         System.out.println(d);
32     }
33 }

9、异常的格式变形

 1 package cn.itcast_07;
 2 
 3 /*
 4  * 面试题:
 5  * 1:final,finally和finalize的区别
 6  * final:最终的意思,可以修饰类,成员变量,成员方法
 7  *         修饰类,类不能被继承
 8  *         修饰变量,变量是常量
 9  *         修饰方法,方法不能被重写
10  * finally:是异常处理的一部分,用于释放资源。
11  *         一般来说,代码肯定会执行,特殊情况:在执行到finally之前jvm退出了
12  * finalize:是Object类的一个方法,用于垃圾回收
13  * 
14  * 2:如果catch里面有return语句,请问finally里面的代码还会执行吗?
15  *   如果会,请问是在return前,还是return后。
16  *        会。前。
17  * 
18  *      准确的说,应该是在中间。
19  * 
20  * 3:try...catch...finally的格式变形
21  *         A:try...catch...finally
22  *         B:try...catch
23  *         C:try...catch...catch...
24  *         D:try...catch...catch...finally
25  *         E:try...finally
26  *             这种做法的目前是为了释放资源。
27  */
28 public class FinallyDemo2 {
29     public static void main(String[] args) {
30         System.out.println(getInt());
31     }
32 
33     public static int getInt() {
34         int a = 10;
35         try {
36             System.out.println(a / 0);
37             a = 20;
38         } catch (ArithmeticException e) {
39             a = 30;
40             return a;
41             /*
42              * return a在程序执行到这一步的时候,这里不是return a而是return 30;这个返回路径就形成了。
43              * 但是呢,它发现后面还有finally,所以继续执行finally的内容,a=40
44              * 再次回到以前的返回路径,继续走return 30;
45              */
46         } finally {
47             a = 40;
48             return a;//如果这样结果就是40了。
49         }
50         // return a;
51     }
52 }

10、自定义异常的实现和测试

 1 package cn.itcast_08;
 2 
 3 /*
 4  * java不可能对所有的情况都考虑到,所以,在实际的开发中,我们可能需要自己定义异常。
 5  * 而我们自己随意的写一个类,是不能作为异常类来看的,要想你的类是一个异常类,就必须继承自Exception或者RuntimeException
 6  * 
 7  * 两种方式:
 8  * A:继承Exception
 9  * B:继承RuntimeException
10  */
11 public class MyException extends Exception {
12     public MyException() {
13     }
14 
15     public MyException(String message) {
16         super(message);
17     }
18 }
19 
20 // public class MyException extends RuntimeException {
21 //
22 // }
 1 package cn.itcast_08;
 2 
 3 public class Teacher {
 4     public void check(int score) throws MyException {
 5         if (score > 100 || score < 0) {
 6             throw new MyException("分数必须在0-100之间");
 7         } else {
 8             System.out.println("分数没有问题");
 9         }
10     }
11 
12     // 针对MyException继承自RuntimeException
13     // public void check(int score) {
14     // if (score > 100 || score < 0) {
15     // throw new MyException();
16     // } else {
17     // System.out.println("分数没有问题");
18     // }
19     // }
20 }
 1 package cn.itcast_08;
 2 
 3 import java.util.Scanner;
 4 
 5 /*
 6  * 自定义异常测试类
 7  */
 8 public class StudentDemo {
 9     public static void main(String[] args) {
10         Scanner sc = new Scanner(System.in);
11         System.out.println("请输入学生成绩:");
12         int score = sc.nextInt();
13 
14         Teacher t = new Teacher();
15         try {
16             t.check(score);
17         } catch (MyException e) {
18             e.printStackTrace();
19         }
20     }
21 }

11、异常的注意事项

 1 package cn.itcast_09;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 /*
 8  * 异常注意事项:
 9  * A:子类重写父类方法时,子类的方法必须抛出相同的异常或父类异常的子类。(父亲坏了,儿子不能比父亲更坏)
10  * B:如果父类抛出了多个异常,子类重写父类时,只能抛出相同的异常或者是他的子集,子类不能抛出父类没有的异常
11  * C:如果被重写的方法没有异常抛出,那么子类的方法绝对不可以抛出异常,如果子类方法内有异常发生,那么子类只能try,不能throws
12  */
13 public class ExceptionDemo {
14 
15 }
16 
17 class Fu {
18     public void show() throws Exception {
19     }
20 
21     public void method() {
22     }
23 }
24 
25 class Zi extends Fu {
26     @Override
27     public void show() throws ArithmeticException {
28 
29     }
30 
31     @Override
32     public void method() {
33         // String s = "2014-11-20";
34         // SimpleDateFormat sdf = new SimpleDateFormat();
35         // Date d = sdf.parse(s);
36         // System.out.println(d);
37     }
38 }

 12、File类的概述和构造方法

 1 package cn.itcast_01;
 2 
 3 import java.io.File;
 4 
 5 /*
 6  * 我们要想实现IO的操作,就必须知道硬盘上文件的表现形式。
 7  * 而Java就提供了一个类File供我们使用。
 8  * 
 9  * File:文件和目录(文件夹)路径名的抽象表示形式
10  * 构造方法:
11  *         File(String pathname):根据一个路径得到File对象
12  *         File(String parent, String child):根据一个目录和一个子文件/目录得到File对象
13  *         File(File parent, String child):根据一个父File对象和一个子文件/目录得到File对象
14  */
15 public class FileDemo {
16     public static void main(String[] args) {
17         // File(String pathname):根据一个路径得到File对象
18         // 把e:\\demo\\a.txt封装成一个File对象
19         File file = new File("E:\\demo\\a.txt");
20 
21         // File(String parent, String child):根据一个目录和一个子文件/目录得到File对象
22         File file2 = new File("E:\\demo", "a.txt");
23 
24         // File(File parent, String child):根据一个父File对象和一个子文件/目录得到File对象
25         File file3 = new File("e:\\demo");
26         File file4 = new File(file3, "a.txt");
27 
28         // 以上三种方式其实效果一样
29     }
30 }

13、File类的创建功能

 1 package cn.itcast_02;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 /*
 7  *创建功能:
 8  *public boolean createNewFile():创建文件 如果存在这样的文件,就不创建了
 9  *public boolean mkdir():创建文件夹 如果存在这样的文件夹,就不创建了
10  *public boolean mkdirs():创建文件夹,如果父文件夹不存在,会帮你创建出来
11  *
12  *骑白马的不一定是王子,可能是班长。
13  *注意:你到底要创建文件还是文件夹,你最清楚,方法不要调错了。
14  */
15 public class FileDemo {
16     public static void main(String[] args) throws IOException {
17         // 需求:我要在e盘目录下创建一个文件夹demo
18         File file = new File("e:\\demo");
19         System.out.println("mkdir:" + file.mkdir());
20 
21         // 需求:我要在e盘目录demo下创建一个文件a.txt
22         File file2 = new File("e:\\demo\\a.txt");
23         System.out.println("createNewFile:" + file2.createNewFile());
24 
25         // 需求:我要在e盘目录test下创建一个文件b.txt
26         // Exception in thread "main" java.io.IOException: 系统找不到指定的路径。
27         // 注意:要想在某个目录下创建内容,该目录首先必须存在。
28         // File file3 = new File("e:\\test\\b.txt");
29         // System.out.println("createNewFile:" + file3.createNewFile());
30 
31         // 需求:我要在e盘目录test下创建aaa目录
32         // File file4 = new File("e:\\test\\aaa");
33         // System.out.println("mkdir:" + file4.mkdir());
34 
35         // File file5 = new File("e:\\test");
36         // File file6 = new File("e:\\test\\aaa");
37         // System.out.println("mkdir:" + file5.mkdir());
38         // System.out.println("mkdir:" + file6.mkdir());
39 
40         // 其实我们有更简单的方法
41         File file7 = new File("e:\\aaa\\bbb\\ccc\\ddd");
42         System.out.println("mkdirs:" + file7.mkdirs());
43 
44         // 看下面的这个东西:
45         File file8 = new File("e:\\liuyi\\a.txt");
46         System.out.println("mkdirs:" + file8.mkdirs());
47     }
48 }

14、File类的删除功能

 1 package cn.itcast_03;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 /*
 7  * 删除功能:public boolean delete()
 8  * 
 9  * 注意:
10  *         A:如果你创建文件或者文件夹忘了写盘符路径,那么,默认在项目路径下。
11  *         B:Java中的删除不走回收站。
12  *         C:要删除一个文件夹,请注意该文件夹内不能包含文件或者文件夹
13  */
14 public class FileDemo {
15     public static void main(String[] args) throws IOException {
16         // 创建文件
17         // File file = new File("e:\\a.txt");
18         // System.out.println("createNewFile:" + file.createNewFile());
19 
20         // 我不小心写成这个样子了
21         File file = new File("a.txt");
22         System.out.println("createNewFile:" + file.createNewFile());
23 
24         // 继续玩几个
25         File file2 = new File("aaa\\bbb\\ccc");
26         System.out.println("mkdirs:" + file2.mkdirs());
27 
28         // 删除功能:我要删除a.txt这个文件
29         File file3 = new File("a.txt");
30         System.out.println("delete:" + file3.delete());
31 
32         // 删除功能:我要删除ccc这个文件夹
33         File file4 = new File("aaa\\bbb\\ccc");
34         System.out.println("delete:" + file4.delete());
35 
36         // 删除功能:我要删除aaa文件夹
37         // File file5 = new File("aaa");
38         // System.out.println("delete:" + file5.delete());
39 
40         File file6 = new File("aaa\\bbb");
41         File file7 = new File("aaa");
42         System.out.println("delete:" + file6.delete());
43         System.out.println("delete:" + file7.delete());
44     }
45 }

15、File类的重命名功能

 1 package cn.itcast_04;
 2 
 3 import java.io.File;
 4 
 5 /*
 6  * 重命名功能:public boolean renameTo(File dest)
 7  *         如果路径名相同,就是改名。
 8  *         如果路径名不同,就是改名并剪切。
 9  * 
10  * 路径以盘符开始:绝对路径    c:\\a.txt
11  * 路径不以盘符开始:相对路径    a.txt
12  */
13 public class FileDemo {
14     public static void main(String[] args) {
15         // 创建一个文件对象
16         // File file = new File("林青霞.jpg");
17         // // 需求:我要修改这个文件的名称为"东方不败.jpg"
18         // File newFile = new File("东方不败.jpg");
19         // System.out.println("renameTo:" + file.renameTo(newFile));
20 
21         File file2 = new File("东方不败.jpg");
22         File newFile2 = new File("e:\\林青霞.jpg");
23         System.out.println("renameTo:" + file2.renameTo(newFile2));
24     }
25 }

16、File类的判断功能

 1 package cn.itcast_05;
 2 
 3 import java.io.File;
 4 
 5 /*
 6  * 判断功能:
 7  * public boolean isDirectory():判断是否是目录
 8  * public boolean isFile():判断是否是文件
 9  * public boolean exists():判断是否存在
10  * public boolean canRead():判断是否可读
11  * public boolean canWrite():判断是否可写
12  * public boolean isHidden():判断是否隐藏
13  */
14 public class FileDemo {
15     public static void main(String[] args) {
16         // 创建文件对象
17         File file = new File("a.txt");
18 
19         System.out.println("isDirectory:" + file.isDirectory());// false
20         System.out.println("isFile:" + file.isFile());// true
21         System.out.println("exists:" + file.exists());// true
22         System.out.println("canRead:" + file.canRead());// true
23         System.out.println("canWrite:" + file.canWrite());// true
24         System.out.println("isHidden:" + file.isHidden());// false
25     }
26 }

17、File类的获取功能

 1 package cn.itcast_06;
 2 
 3 import java.io.File;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 /*
 8  * 获取功能:
 9  * public String getAbsolutePath():获取绝对路径
10  * public String getPath():获取相对路径
11  * public String getName():获取名称
12  * public long length():获取长度。字节数
13  * public long lastModified():获取最后一次的修改时间,毫秒值
14  */
15 public class FileDemo {
16     public static void main(String[] args) {
17         // 创建文件对象
18         File file = new File("demo\\test.txt");
19 
20         System.out.println("getAbsolutePath:" + file.getAbsolutePath());
21         System.out.println("getPath:" + file.getPath());
22         System.out.println("getName:" + file.getName());
23         System.out.println("length:" + file.length());
24         System.out.println("lastModified:" + file.lastModified());
25 
26         // 1416471971031
27         Date d = new Date(1416471971031L);
28         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
29         String s = sdf.format(d);
30         System.out.println(s);
31     }
32 }

18、File类的高级获取功能

 1 package cn.itcast_07;
 2 
 3 import java.io.File;
 4 
 5 /*
 6  * 获取功能:
 7  * public String[] list():获取指定目录下的所有文件或者文件夹的名称数组
 8  * public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组
 9  */
10 public class FileDemo {
11     public static void main(String[] args) {
12         // 指定一个目录
13         File file = new File("e:\\");
14 
15         // public String[] list():获取指定目录下的所有文件或者文件夹的名称数组
16         String[] strArray = file.list();
17         for (String s : strArray) {
18             System.out.println(s);
19         }
20         System.out.println("------------");
21 
22         // public File[] listFiles():获取指定目录下的所有文件或者文件夹的File数组
23         File[] fileArray = file.listFiles();
24         for (File f : fileArray) {
25             System.out.println(f.getName());
26         }
27     }
28 }

 19、输出指定目录下指定后缀名的文件名称案例

 1 package cn.itcast_08;
 2 
 3 import java.io.File;
 4 
 5 /*
 6  * 判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称
 7  * 
 8  * 分析:
 9  *         A:封装e判断目录
10  *         B:获取该目录下所有文件或者文件夹的File数组
11  *         C:遍历该File数组,得到每一个File对象,然后判断
12  *         D:是否是文件
13  *             是:继续判断是否以.jpg结尾
14  *                 是:就输出该文件名称
15  *                 否:不搭理它
16  *             否:不搭理它
17  */
18 public class FileDemo {
19     public static void main(String[] args) {
20         // 封装e判断目录
21         File file = new File("e:\\");
22 
23         // 获取该目录下所有文件或者文件夹的File数组
24         File[] fileArray = file.listFiles();
25 
26         // 遍历该File数组,得到每一个File对象,然后判断
27         for (File f : fileArray) {
28             // 是否是文件
29             if (f.isFile()) {
30                 // 继续判断是否以.jpg结尾
31                 if (f.getName().endsWith(".jpg")) {
32                     // 就输出该文件名称
33                     System.out.println(f.getName());
34                 }
35             }
36         }
37     }
38 }

20、文件过滤器改进输出指定目录下指定后缀名的文件名称案例

 1 package cn.itcast_08;
 2 
 3 import java.io.File;
 4 import java.io.FilenameFilter;
 5 
 6 /*
 7  * 判断E盘目录下是否有后缀名为.jpg的文件,如果有,就输出此文件名称
 8  * A:先获取所有的,然后遍历的时候,依次判断,如果满足条件就输出。
 9  * B:获取的时候就已经是满足条件的了,然后输出即可。
10  * 
11  * 要想实现这个效果,就必须学习一个接口:文件名称过滤器
12  * public String[] list(FilenameFilter filter)
13  * public File[] listFiles(FilenameFilter filter)
14  */
15 public class FileDemo2 {
16     public static void main(String[] args) {
17         // 封装e判断目录
18         File file = new File("e:\\");
19 
20         // 获取该目录下所有文件或者文件夹的String数组
21         // public String[] list(FilenameFilter filter)
22         String[] strArray = file.list(new FilenameFilter() {
23             @Override
24             public boolean accept(File dir, String name) {
25                 // return false;
26                 // return true;
27                 // 通过这个测试,我们就知道了,到底把这个文件或者文件夹的名称加不加到数组中,取决于这里的返回值是true还是false
28                 // 所以,这个的true或者false应该是我们通过某种判断得到的
29                 // System.out.println(dir + "---" + name);
30                 // File file = new File(dir, name);
31                 // // System.out.println(file);
32                 // boolean flag = file.isFile();
33                 // boolean flag2 = name.endsWith(".jpg");
34                 // return flag && flag2;
35                 return new File(dir, name).isFile() && name.endsWith(".jpg");
36             }
37         });
38 
39         // 遍历
40         for (String s : strArray) {
41             System.out.println(s);
42         }
43     }
44 }

21、批量修改文件名称案例

 1 package cn.itcast_09;
 2 
 3 import java.io.File;
 4 
 5 /*
 6  * 需求:把E:\评书\三国演义下面的视频名称修改为
 7  *         00?_介绍.avi
 8  * 
 9  * 思路:
10  *         A:封装目录
11  *         B:获取该目录下所有的文件的File数组
12  *         C:遍历该File数组,得到每一个File对象
13  *         D:拼接一个新的名称,然后重命名即可。
14  */
15 public class FileDemo {
16     public static void main(String[] args) {
17         // 封装目录
18         File srcFolder = new File("E:\\评书\\三国演义");
19 
20         // 获取该目录下所有的文件的File数组
21         File[] fileArray = srcFolder.listFiles();
22 
23         // 遍历该File数组,得到每一个File对象
24         for (File file : fileArray) {
25             // System.out.println(file);
26             // E:\评书\三国演义\三国演义_001_[评书网-今天很高兴,明天就IO了]_桃园三结义.avi
27             // 改后:E:\评书\三国演义\001_桃园三结义.avi
28             String name = file.getName(); // 三国演义_001_[评书网-今天很高兴,明天就IO了]_桃园三结义.avi
29 
30             int index = name.indexOf("_");
31             String numberString = name.substring(index + 1, index + 4);
32             // System.out.println(numberString);
33 
34             // int startIndex = name.lastIndexOf('_');
35             // int endIndex = name.lastIndexOf('.');
36             // String nameString = name.substring(startIndex + 1, endIndex);
37             // System.out.println(nameString);
38             int endIndex = name.lastIndexOf('_');
39             String nameString = name.substring(endIndex);
40 
41             String newName = numberString.concat(nameString); // 001_桃园三结义.avi
42             // System.out.println(newName);
43 
44             File newFile = new File(srcFolder, newName); // E:\\评书\\三国演义\\001_桃园三结义.avi
45 
46             // 重命名即可
47             file.renameTo(newFile);
48         }
49     }
50 }

 --前生今生来生 与你相遇在每一个梦里 拂袖唤漫天流萤 掌心微光谁眼中倒映

posted @ 2017-06-03 22:41  花醉红尘  阅读(259)  评论(0编辑  收藏  举报