【原】Java学习笔记033 - IO

 1 package cn.temptation;
 2 
 3 public class Sample01 {
 4     public static void main(String[] args) {
 5         // 需求:继承关系中爷爷类、父类、子类,现在父类行为有了增强,如何不影响子类?
 6         // 思路:首先考虑让父类实现增强能力的接口,但是这样做,会让继承子类也具有增强能力
 7 //        Son son = new Son();
 8 //        son.method();
 9         
10         //      其次考虑让父类中的增强行为方法设置为private,这样子类是没有继承,但是外部访问父类对象的该方法也无法访问
11 //        Father father = new Father();
12         // 语法错误:The method methodEx() from the type Father is not visible
13 //        father.methodEx();
14         
15         //      再次考虑对父类使用final关键字,这就让父类断子绝孙,没有子类能继承了;
16         //      如果对父类的成员方法使用final关键字,只是不让子类去重写继承过来的父类的成员方法,并不是不能使用
17 //        Son son = new Son();
18 //        son.show();
19     }
20 }
21 
22 //interface IAbility {
23 //    public abstract void method();
24 //}
25 //
26 //class Father implements IAbility {
27 //    @Override
28 //    public void method() {
29 //        
30 //    }
31 //    
32 //    private void methodEx() {
33 //        
34 //    }
35 //    
36 //    public final void show() {
37 //        
38 //    }
39 //}
40 //
41 //class Son extends Father {
42 //    // 语法错误:Cannot override the final method from Father
43 ////    @Override
44 ////    public void show() {
45 ////        
46 ////    }
47 //}
 1 package cn.temptation;
 2 
 3 public class Sample02 {
 4     public static void main(String[] args) {
 5         // 需求:继承关系中爷爷类、父类、子类,现在父类行为有了增强,如何不影响子类?
 6         
 7         // 思路:这种共性问题,同样通过设计模式解决,使用"装饰模式(修饰模式)"
 8         //      制作和继承链无关的新的类,对有增强行为的类进行装饰(修饰)
 9         
10         // 继承链上的子类的行为不受影响
11         Son son = new Son();
12         son.methodBySon();
13         son.methodByFather();
14         son.methodByGrandFather();
15         // 显然父类的增强行为和继承子类无关
16         // 语法错误:The method methodEx() is undefined for the type Son
17 //        son.methodEx();
18         System.out.println("-----------------");
19         
20         // 使用行为未增强的父类
21         Father father = new Father();
22         father.methodByFather();
23         father.methodByGrandFather();
24         System.out.println("-----------------");
25         
26         // 使用行为增强的父类
27         FatherEx fatherEx = new FatherEx(new Father());
28         // 调用其增强的行为
29         fatherEx.methodEx();
30         // 调用之前的父类的行为
31         fatherEx.getFather().methodByFather();
32         fatherEx.getFather().methodByGrandFather();
33     }
34 }
35 
36 class GrandFather {
37     public void methodByGrandFather() {
38         System.out.println("爷爷类的成员方法");
39     }
40 }
41 
42 class Father extends GrandFather {
43     public void methodByFather() {
44         System.out.println("父类的成员方法");
45     }
46 }
47 
48 /**
49  * 对Father类进行装饰
50  * 既然是对Father类的对象进行装饰,那么应该有Father类的实例对象
51  * 考虑通过参数传入,选择最简单的构造函数的参数传入
52  */
53 class FatherEx {
54     // 成员变量
55     private Father father = null;
56     
57     // 构造函数
58     public FatherEx(Father father) {
59         this.father = father;
60     }
61 
62     // 成员方法
63     public Father getFather() {
64         return father;
65     }
66 
67     public void setFather(Father father) {
68         this.father = father;
69     }
70     
71     /**
72      * 父类的增强行为
73      */
74     public void methodEx() {
75         System.out.println("父类的增强成员方法");
76     }
77 }
78 
79 class Son extends Father {
80     public void methodBySon() {
81         System.out.println("子类的成员方法");
82     }
83 }
 1 package cn.temptation;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 public class Sample03 {
 7     public static void main(String[] args) {
 8         /*
 9          * 为了实现IO(Input/Output)的操作,对硬盘上的文件的形式有一个了解,即  目录(文件夹) 和  文件
10          * Java语言中提供了  File类   方便操作目录  和  文件
11          * 
12          * 类 File:文件和目录路径名的抽象表示形式。
13          * 
14          * 构造函数:
15          * 1、File(String pathname):通过将给定路径名字符串转换为抽象路径名来创建一个新 File实例。
16          * 2、File(String parent, String child):根据 parent 路径名字符串和 child 路径名字符串创建一个新 File实例。
17          * 3、File(File parent, String child):根据 parent 抽象路径名和 child 路径名字符串创建一个新 File实例。
18          * 
19          * 成员方法:
20          * 1、boolean createNewFile():当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。
21          *    返回:如果指定的文件不存在并成功地创建,则返回 true;如果指定的文件已经存在,则返回 false  
22          */
23         
24         // 因为路径字符串中存在反斜杠,所以需要进行转义
25         // 语法错误:Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \"  \'  \\ )
26 //        File file1 = new File("D:\abc.txt");
27         
28         // 正确写法:使用两个反斜杠转义反斜杠
29         File file1 = new File("D:\\abc.txt");
30         System.out.println(file1);        // D:\abc.txt
31         
32         // 下面语句第一次执行会返回true的结果,再次执行会返回false的结果
33         try {
34             System.out.println(file1.createNewFile());
35         } catch (IOException e) {
36             e.printStackTrace();
37         }
38         
39         File file2 = new File("D:\\iotest", "abc.txt");
40         System.out.println(file2);        // D:\iotest\abc.txt
41         
42         // 执行出错:java.io.IOException: 系统找不到指定的路径。
43         // 因为没有iotest这个目录,手工创建iotest目录后,再执行,返回true的结果
44         try {
45             System.out.println(file2.createNewFile());
46         } catch (IOException e) {
47             e.printStackTrace();
48         }
49         
50         File file3 = new File("D:\\iotest");
51         File file4 = new File(file3, "abc.txt");
52         System.out.println(file4);        // D:\iotest\abc.txt
53         
54         try {
55             System.out.println(file4.createNewFile());
56         } catch (IOException e) {
57             e.printStackTrace();
58         }
59         
60         /*
61          * File类的常用字段:
62          * static String separator:与系统有关的默认名称分隔符,为了方便,它被表示为一个字符串。 
63          */
64         File file5 = new File("d:" + File.separator + "iotest" + File.separator + "abc.txt");
65         System.out.println(file5);        // d:\iotest\abc.txt
66         
67         try {
68             System.out.println(file5.createNewFile());
69         } catch (IOException e) {
70             e.printStackTrace();
71         }
72     }
73 }
 1 package cn.temptation;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 public class Sample04 {
 7     public static void main(String[] args) {
 8         /*
 9          * File类的常用成员方法:
10          * 1、boolean mkdir():创建此抽象路径名指定的目录。 
11          */
12         // 创建目录
13         File file1 = new File("D:\\iotest");
14         System.out.println(file1.mkdir());
15         
16         // 创建文件
17         File file2 = new File("D:\\iotest\\test.txt");
18         try {
19             System.out.println(file2.createNewFile());
20         } catch (IOException e) {
21             e.printStackTrace();
22         }
23     }
24 }
 1 package cn.temptation;
 2 
 3 import java.io.File;
 4 
 5 public class Sample05 {
 6     public static void main(String[] args) {
 7         /*
 8          * File类的常用成员方法:
 9          * 1、boolean mkdirs():创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。 
10          */
11         
12         // 需求:创建这样的目录:D:\aaa\bbb\ccc
13 //        File file1 = new File("D:\\aaa\\bbb\\ccc");
14 //        System.out.println(file1.mkdir());            // false,使用mkdir创建多级目录,不可行
15         
16         // 如下一级一级的创建目录可行,但是太麻烦
17 //        File file2 = new File("D:\\aaa");
18 //        System.out.println(file2.mkdir());
19 //        File file3 = new File("D:\\aaa\\bbb");
20 //        System.out.println(file3.mkdir());
21 //        File file4 = new File("D:\\aaa\\bbb\\ccc");
22 //        System.out.println(file4.mkdir());
23         
24         // 使用mkdirs创建多级目录
25 //        File file5 = new File("D:\\aaa\\bbb\\ccc");
26 //        System.out.println(file5.mkdirs());
27         
28         // 问题:如下语句会执行出什么样的结果?
29         // 答:返回false的结果,不会产生iotest目录以及在其中产生test.txt目录
30         File file6 = new File("D:\\iotest\test.txt");
31         System.out.println(file6.mkdirs());        // false
32         
33         // 注意:进行IO操作之前,首先要确定生成的是目录还是文件
34     }
35 }
 1 package cn.temptation;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 public class Sample06 {
 7     public static void main(String[] args) {
 8         /*
 9          * File类的常用成员方法: 
10          * 1、boolean delete():删除此抽象路径名表示的文件或目录。
11          */
12 
13         // 创建目录
14         File file1 = new File("D:\\iotest");
15         System.out.println("创建目录:" + file1.mkdir());        // 创建目录:true
16         
17         // 在创建出来的目录下创建文件
18         File file2 = new File("D:\\iotest\\test.txt");
19         try {
20             System.out.println("创建文件:" + file2.createNewFile());    // 创建文件:true
21         } catch (IOException e) {
22             e.printStackTrace();
23         }
24         
25         // 删除非空目录iotest
26         System.out.println("删除目录:" + file1.delete());    // 删除目录:false
27         
28         // 删除非空目录中的文件,再删除这个目录
29         System.out.println("先删除文件:" + file2.delete());    // 先删除文件:true
30         System.out.println("再删除目录:" + file1.delete());    // 再删除目录:true
31     }
32 }
 1 package cn.temptation;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 public class Sample07 {
 7     public static void main(String[] args) {
 8         /*
 9          * File类使用时,如果不带盘符及路径名,生成的目录 或 文件 在当前的工程目录下
10          */
11         File file1 = new File("iotest");
12         System.out.println(file1.mkdir());
13         
14         File file2 = new File("abc.txt");
15         try {
16             System.out.println(file2.createNewFile());
17         } catch (IOException e) {
18             e.printStackTrace();
19         }
20         
21         File file3 = new File("iotest\\abc.txt");
22         try {
23             System.out.println(file3.createNewFile());
24         } catch (IOException e) {
25             e.printStackTrace();
26         }
27         
28         File file4 = new File("iotest\\aaa\\bbb\\ccc");
29         System.out.println(file4.mkdirs());
30         
31         System.out.println("删除文件:" + file2.delete());
32         
33         // 对于有子目录的目录,删除时同样也要先删除其子目录
34         System.out.println("删除目录:" + (new File("iotest\\aaa")).delete());    // 删除目录:false
35     }
36 }
 1 package cn.temptation;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 public class Sample08 {
 7     public static void main(String[] args) {
 8         /*
 9          * File类的常用成员方法:
10          * 1、boolean renameTo(File dest):重新命名此抽象路径名表示的文件。
11          * 
12          * 注意:
13          * 1、如果路径名称相同,renameTo方法做的是改名的操作
14          * 2、如果路径名称不相同,renameTo方法做的不仅改名,而且剪切并粘贴到新的路径下
15          */
16         File file1 = new File("a.txt");
17         File file2 = new File("b.txt");
18         
19         // 先创建出a.txt文件
20         try {
21             System.out.println("创建a.txt:" + file1.createNewFile());    // 创建a.txt:true
22         } catch (IOException e) {
23             e.printStackTrace();
24         }
25         
26         // 再重新命名
27         System.out.println("a.txt改名为b.txt:" + file1.renameTo(file2));    // a.txt改名为b.txt:true
28         
29         File file3 = new File("D:\\c.txt");
30         // 再重新命名
31         System.out.println("a.txt改名为D:\\c.txt:" + file1.renameTo(file3));    // a.txt改名为D:\c.txt:false
32         System.out.println("b.txt改名为D:\\c.txt:" + file2.renameTo(file3));    // b.txt改名为D:\c.txt:true
33     }
34 }
 1 package cn.temptation;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 
 6 public class Sample09 {
 7     public static void main(String[] args) {
 8         /*
 9          * File类的常用成员方法:
10          * 
11          * 判断功能:
12          * 1、boolean isDirectory():测试此抽象路径名表示的文件是否是一个目录。
13          * 2、boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
14          * 3、boolean isHidden():测试此抽象路径名指定的文件是否是一个隐藏文件。
15          * 4、boolean exists():测试此抽象路径名表示的文件或目录是否存在。
16          * 5、boolean canRead():测试应用程序是否可以读取此抽象路径名表示的文件。
17          * 6、boolean canWrite():测试应用程序是否可以修改此抽象路径名表示的文件。 
18          */
19         
20         File file = new File("test.txt");
21         
22         try {
23             System.out.println("创建文件:" + file.createNewFile());
24         } catch (IOException e) {
25             e.printStackTrace();
26         }
27         
28         System.out.println("isDirectory:" + file.isDirectory());    // isDirectory:false
29         System.out.println("isFile:" + file.isFile());    // isFile:true
30         System.out.println("isHidden:" + file.isHidden());    // isHidden:false
31         System.out.println("exists:" + file.exists());    // exists:true
32         System.out.println("canRead:" + file.canRead());    // canRead:true
33         System.out.println("canWrite:" + file.canWrite());    // canWrite:true
34     }
35 }
 1 package cn.temptation;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.text.SimpleDateFormat;
 6 import java.util.Date;
 7 
 8 public class Sample10 {
 9     public static void main(String[] args) {
10         /*
11          * File类的常用成员方法:
12          * 
13          * 获取功能:
14          * 1、String getAbsolutePath():返回此抽象路径名的绝对路径名字符串。
15          * 2、String getPath():将此抽象路径名转换为一个路径名字符串。
16          * 3、String getName():返回由此抽象路径名表示的文件或目录的名称。
17          * 4、long length():返回由此抽象路径名表示的文件的长度。
18          * 5、long lastModified():返回此抽象路径名表示的文件最后一次被修改的时间。     
19          */
20         
21         File file = new File("test.txt");
22         
23         try {
24             System.out.println("创建文件:" + file.createNewFile());
25         } catch (IOException e) {
26             e.printStackTrace();
27         }
28         
29         System.out.println("getAbsolutePath:" + file.getAbsolutePath());    // getAbsolutePath:D:\workspace\Day20170920_IO\test.txt
30         System.out.println("getPath:" + file.getPath());    // getPath:test.txt
31         System.out.println("getName:" + file.getName());    // getName:test.txt
32         System.out.println("length:" + file.length());        // length:0
33         System.out.println("lastModified:" + file.lastModified());    // lastModified:1505876385640
34         
35         // 转换为日期时间
36         Date date = new Date(1505876385640L);
37         System.out.println(date);        // Wed Sep 20 10:59:45 CST 2017
38         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
39         System.out.println(sdf.format(date));    // 2017-09-20 10:59:45
40     }
41 }
 1 package cn.temptation;
 2 
 3 import java.io.File;
 4 
 5 public class Sample11 {
 6     public static void main(String[] args) {
 7         /*
 8          * File类的常用成员方法:
 9          * 
10          * 获取功能:
11          * 1、String[] list():返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。 
12          * 2、File[] listFiles():返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。 
13          */
14         
15         File file = new File("C:\\");
16         String[] arr = file.list();        // 隐藏目录 和  文件均可以获取到
17         
18         for (String item : arr) {
19             System.out.println(item);
20         }
21         
22         System.out.println("----------------");
23         
24         File[] files = file.listFiles();
25         
26         for (File item : files) {
27             System.out.println(item);
28         }
29     }
30 }
 1 package cn.temptation;
 2 
 3 import java.io.File;
 4 
 5 public class Sample12 {
 6     public static void main(String[] args) {
 7         // 需求:查找C盘根目录下是否有后缀名为.jpg的文件,如果有就显示出来
 8         
 9         // 思路:
10         // 1、获取C盘根目录的File对象
11         // 2、获取C盘根目录的所有目录和文件
12         // 3、使用File类的判断功能isFile方法判断是否为文件
13         // 4、如果是文件,再判断后缀名为.jpg(根据String类的成员方法:boolean endsWith(String suffix)测试此字符串是否以指定的后缀结束。 )
14         
15         File file = new File("C:\\");
16         
17         File[] files = file.listFiles();
18         
19         for (File item : files) {
20             if (item.isFile()) {
21                 if (item.getName().endsWith(".jpg")) {
22                     System.out.println(item);
23                 }
24             }
25         }
26     }
27 }
 1 package cn.temptation;
 2 
 3 import java.io.File;
 4 import java.io.FilenameFilter;
 5 
 6 public class Sample13 {
 7     public static void main(String[] args) {
 8         /*
 9          * File类的常用成员方法:
10          * 1、File[] listFiles(FilenameFilter filter):返回抽象路径名数组,这些路径名表示此抽象路径名表示的目录中满足指定过滤器的文件和目录。
11          * 
12          * 接口 FilenameFilter:实现此接口的类实例可用于过滤器文件名。Abstract Window Toolkit 的文件对话框组件使用这些实例过滤 File 类的 list 方法中的目录清单。
13          * 
14          * FilenameFilter接口的常用成员方法:
15          * 1、boolean accept(File dir, String name):测试指定文件是否应该包含在某一文件列表中。
16          *         参数:dir - 被找到的文件所在的目录。        name - 文件的名称。 
17          */
18         
19         File file = new File("C:\\");
20         
21         String[] arr = file.list(new FilenameFilter() {
22             @Override
23             public boolean accept(File dir, String name) {
24                 boolean result = false;
25                 
26                 // 写法1
27 //                if (new File(dir, name).isFile()) {
28 //                    if (name.endsWith(".jpg")) {
29 //                        result = true;
30 //                    }
31 //                }
32                 
33                 // 写法2
34 //                result = new File(dir, name).isFile() && name.endsWith(".jpg");
35 //                
36 //                return result;
37                 
38                 // 写法3
39                 return new File(dir, name).isFile() && name.endsWith(".jpg");
40             }
41         });
42         
43         for (String item : arr) {
44             System.out.println(item);
45         }
46     }
47 }
 1 package cn.temptation;
 2 
 3 import java.io.File;
 4 import java.util.Scanner;
 5 
 6 public class Sample14 {
 7     public static void main(String[] args) {
 8         // 需求:键盘录入一个路径和文件后缀名,查找该路径下所有该文件后缀名的文件并显示出来
 9         //      比如:查找D:\workspace下的所有.java文件,注意可能是多级目录
10         
11         // 思路:
12         // 因为获取指定路径的File对象可能是一个目录,也可能是一个文件,如果是文件,只要判断一下是否为指定后缀名的文件即可
13         // 如果是目录,获取目录中内容进行判断
14         // 显然,多级目录的操作考虑使用递归
15         
16         // 接收键盘的录入
17         Scanner input = new Scanner(System.in);
18         System.out.println("输入一个路径:(例如:D:\\workspace)");
19         String path = input.nextLine();
20         System.out.println("输入文件后缀名:(例如:.java)");
21         String suffix = input.nextLine();
22         input.close();
23         
24         // 创建File对象
25         File file = new File(path);
26         
27         // 如下代码,如果找到的File对象是目录时,还要再查找目录中的内容进行判断
28         // 所以考虑使用递归进行改写
29         // 使用递归时,注意递归的终止条件,否则会形成死循环
30         // 这里递归的终止条件是找到的File对象是文件就不再递归
31 //        File[] files = file.listFiles();
32 //        for (File item : files) {
33 //            if (item.isFile()) {    // 是文件
34 //                if (item.getName().endsWith(suffix)) {
35 //                    System.out.println(item);
36 //                }
37 //            } else {                // 是目录
38 //                File[] sonFiles = item.listFiles();
39 //                for (File sonItem : sonFiles) {
40 //                    if (sonItem.isFile()) {        // 是文件
41 //                        if (sonItem.getName().endsWith(suffix)) {
42 //                            System.out.println(sonItem);
43 //                        }
44 //                    } else {                    // 是目录
45 //                        sonItem.listFiles();
46 //                    }
47 //                }
48 //            }
49 //        }
50         
51         // 调用递归方法
52         getAllFolderAndFile(file, suffix);
53         
54         // 注意:
55         // 1、该操作传入的文件路径不应该是只有盘符,
56         //    因为windows操作系统会在每个盘符下都创建一个回收站目录,该目录使用listFiles时会得到null的结果,进而产生空指针异常
57         // 2、手工创建空目录,使用listFiles时会得到空的File数组,遍历不会出错
58     }
59     
60     /**
61      * 获取所有目录和文件
62      * @param file        File对象
63      * @param suffix    文件后缀名
64      */
65     public static void getAllFolderAndFile(File file, String suffix) {
66         File[] files = file.listFiles();
67         for (File item : files) {
68             if (item.isFile()) {    // 是文件
69                 if (item.getName().endsWith(suffix)) {
70                     System.out.println(item);
71                 }
72             } else {                // 是目录
73                 getAllFolderAndFile(item, suffix);
74             }
75         }
76     }
77 }
 1 package cn.temptation;
 2 
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 
 6 public class Sample15 {
 7     public static void main(String[] args) throws IOException {
 8         /*
 9          * IO流:
10          * 
11          * 现实世界中有很多流的概念:水流、气流、电流,都是物质的移动
12          * Java中的流是为了实现数据的移动
13          * 
14          * 李白的诗句:"黄河之水天上来,奔流到海不复回"
15          * 源头:天上        目标(终点):海
16          * 
17          * 数据流也是流,也有源头 和 终点,应用程序像水坝一样拦在中间
18          * 
19          * 站在应用程序的角度,将流分为:
20          * 1、按流向分类:
21          * A:输入流----->输入给应用程序(读取数据)----->从源头读取数据
22          * B:输出流----->输出给目标(写出数据)----->写出数据给目标
23          * 
24          * 2、按数据类型分类:
25          * A:字节流(1字节 = 8bit)
26          *         字节输入流:读取数据-----> InputStream  此抽象类是表示字节输入流的所有类的超类。
27          *         字节输出流:写出数据-----> OutputStream 此抽象类是表示输出字节流的所有类的超类。
28          * B:字符流(1字符=2字节=16bit)(注意:如果使用UTF-8字符集,非英文数字字符使用3个字节存储)
29          *         字符输入流:读取数据-----> Reader 用于读取字符流的抽象类。
30          *         字符输出流:写出数据-----> Writer 用于写入字符流的抽象类。
31          * 
32          * 
33          * 
34          * 类 OutputStream:此抽象类是表示输出字节流的所有类的超类。输出流接受输出字节并将这些字节发送到某个接收器。 
35          * 需要定义 OutputStream 子类的应用程序必须始终提供至少一种可写入一个输出字节的方法。 
36          * 
37          * 类 FileOutputStream:文件输出流是用于将数据写入 File 或 FileDescriptor 的输出流。
38          * 
39          * FileOutputStream类的构造函数:
40          * FileOutputStream(String name):创建一个向具有指定名称的文件中写入数据的输出文件流。
41          * 
42          * FileOutputStream类的常用成员方法:
43          * 1、void close():关闭此文件输出流并释放与此流有关的所有系统资源。 
44          * 2、void write(byte[] b):将 b.length个字节从指定byte数组写入此文件输出流中。 
45          */
46         
47         FileOutputStream fos = new FileOutputStream("D:\\test01.txt");
48         
49         fos.write("abc".getBytes());
50         
51         // 释放资源
52         fos.close();
53     }
54 }
 1 package cn.temptation;
 2 
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 
 6 public class Sample16 {
 7     public static void main(String[] args) throws IOException {
 8         /*
 9          * FileOutputStream类的常用成员方法:
10          * 1、void write(int b):将指定字节写入此文件输出流。
11          * 2、void write(byte[] b):将 b.length 个字节从指定 byte 数组写入此文件输出流中。 
12          * 3、void write(byte[] b, int off, int len):将指定 byte 数组中从偏移量 off开始的 len个字节写入此文件输出流。  
13          */
14         
15         FileOutputStream fos = new FileOutputStream("D:\\test01.txt");
16         
17         // 写出一个字节
18         fos.write(97);        // 先写出一个a
19         
20         byte[] arr = { 97, 98, 99 };
21         fos.write(arr);        // 接着写出abc
22         
23         fos.write(arr, 1, 1);    // 接着写出b
24         
25         // 释放资源
26         fos.close();
27     }
28 }
 1 package cn.temptation;
 2 
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 
 6 public class Sample17 {
 7     public static void main(String[] args) throws IOException {
 8         /*
 9          * FileOutputStream类的构造函数:
10          * 1、FileOutputStream(File file, boolean append):创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
11          *         参数:file - 为了进行写入而打开的文件。        append - 如果为 true,则将字节写入文件末尾处,而不是写入文件开始处。 
12          */
13         
14         // 接着上一个例子,test01.txt中原先有内容为"aabcb",设置构造函数的append参数为true,不会覆盖之前的内容,在文件末尾追加
15         // 设置构造函数的append参数为false,覆盖之前的内容
16 //        FileOutputStream fos = new FileOutputStream("D:\\test01.txt", true);    // 写入的结果为:aabcb添加的内容0添加的内容1添加的内容2
17         FileOutputStream fos = new FileOutputStream("D:\\test01.txt", false);    // 写入的结果为:添加的内容0添加的内容1添加的内容2
18         
19         for (int i = 0; i < 3; i++) {
20             fos.write(("添加的内容" + i).getBytes());
21         }
22         
23         fos.close();
24     }
25 }
 1 package cn.temptation;
 2 
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 
 6 public class Sample18 {
 7     public static void main(String[] args) {
 8         // 需求:使用try...catch...finally的形式使用FileOutputStream
 9         FileOutputStream fos = null;
10         
11         try {
12             fos = new FileOutputStream("D:\\test01.txt");
13             
14             fos.write("abc".getBytes());
15         } catch (Exception e) {
16             e.printStackTrace();
17         } finally {
18             if (fos != null) {
19                 try {
20                     fos.close();
21                 } catch (IOException e) {
22                     e.printStackTrace();
23                 }
24             }
25         }
26     }
27 }
 1 package cn.temptation;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.IOException;
 5 
 6 public class Sample19 {
 7     public static void main(String[] args) throws IOException {
 8         /*
 9          * 类 FileInputStream:从文件系统中的某个文件中获得输入字节。哪些文件可用取决于主机环境。
10          * FileInputStream用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader。
11          * 
12          * FileInputStream类的构造函数:
13          * FileInputStream(String name):通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。
14          * 
15          * FileInputStream类的常用成员方法:
16          * 1、void close():关闭此文件输入流并释放与此流有关的所有系统资源。 
17          * 2、int read():从此输入流中读取一个数据字节。
18          *         返回:下一个数据字节;如果已到达文件末尾,则返回 -1。  
19          */
20         
21         // test01.txt文件中有内容为"abc"
22         FileInputStream fis = new FileInputStream("D:\\test01.txt");
23         
24         // 下句从输入流中读取一个数据字节
25 //        System.out.println(fis.read());        // 97
26         
27         // 循环读取
28         // 如下写法错误,一次循环中调用了两次read方法,对于"abc"的读取,会得到"98、-1"的结果
29 //        while (fis.read() != -1) {
30 //            System.out.println(fis.read());
31 //        }
32         
33         // 正确写法
34         int ch = 0;
35         while ((ch = fis.read()) != -1) {
36             System.out.println((char) ch);
37         }
38 
39         fis.close();
40     }
41 }
 1 package cn.temptation;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 
 7 public class Sample20 {
 8     public static void main(String[] args) throws IOException {
 9         // 需求:从test01.txt文件中使用字节流读取内容,再使用字节流写入到test02.txt文件中
10         
11         // 思路:
12         // 源头:test01.txt----->读取数据,使用FileInputStream
13         // 目标:test02.txt----->写出数据,使用FileOutputStream
14         
15         FileInputStream fis = new FileInputStream("D:\\test01.txt");
16         FileOutputStream fos = new FileOutputStream("D:\\test02.txt");
17         
18         // 一边读,一边写
19         int ch = 0;
20         while ((ch = fis.read()) != -1) {
21             // 注意:如果test01.txt中写的是中文内容,读取时会显示为乱码(不论是否修改txt文件的编码格式),但是写出到test02.txt中还会时正常的中文
22             System.out.println((char)ch);
23             // 伴随着读的操作就去做写的操作
24             fos.write(ch);
25         }
26         
27         fos.close();
28         fis.close();
29     }
30 }
 1 package cn.temptation;
 2 
 3 import java.util.Arrays;
 4 
 5 public class Sample21 {
 6     public static void main(String[] args) {
 7         /*
 8          * 在UTF-8编码下存储非英文非数字字符,每一个非英数字符会占用三个字节存储
 9          */
10         String str = "中国";
11         byte[] arr = str.getBytes();
12         
13         for (byte item : arr) {
14             System.out.print(item);        // -28-72-83-27-101-67
15         }
16         
17         System.out.println();
18         
19         System.out.println(Arrays.toString(arr));    // [-28, -72, -83, -27, -101, -67]
20     }
21 }
 1 package cn.temptation;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 
 7 public class Sample22 {
 8     public static void main(String[] args) throws IOException {
 9         // 需求:读取图片"陆逊.jpg",写出成新的图片"偶像.jpg"
10         FileInputStream fis = new FileInputStream("D:\\陆逊.jpg");
11         FileOutputStream fos = new FileOutputStream("D:\\偶像.jpg");
12         
13         // 一边读,一边写
14         int ch = 0;
15         while ((ch = fis.read()) != -1) {
16             // 伴随着读的操作就去做写的操作
17             fos.write(ch);
18         }
19         
20         fos.close();
21         fis.close();
22     }
23 }
 1 package cn.temptation;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.IOException;
 5 
 6 public class Sample23 {
 7     public static void main(String[] args) throws IOException {
 8         /*
 9          * FileInputStream类的常用成员方法:
10          * 1、int read(byte[] b):从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。
11          *      参数:b - 存储读取数据的缓冲区。数组的长度一般是1024 或 1024的整数倍
12          *      返回:读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。
13          *  
14          * String类的构造函数:
15          * 1、String(byte[] bytes, int offset, int length):通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。
16          */
17         FileInputStream fis = new FileInputStream("D:\\test01.txt");
18         
19         byte[] arr = new byte[1024];
20         int ch = 0;
21         
22 //        while ((ch = fis.read()) != -1) {
23 //            System.out.println((char)ch);    // a    b    c
24 //        }
25         
26         while ((ch = fis.read(arr)) != -1) {
27             System.out.println(ch);            // 读入缓冲区的字节总数为3
28             System.out.println(new String(arr, 0, ch));    // abc
29         }
30         
31         fis.close();
32     }
33 }
 1 package cn.temptation;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 
 7 public class Sample24 {
 8     public static void main(String[] args) throws IOException {
 9         // 需求:从test01.txt文件中读取内容,写出到test02.txt文件中,使用缓冲区
10         
11         FileInputStream fis = new FileInputStream("D:\\test01.txt");
12         FileOutputStream fos = new FileOutputStream("D:\\test02.txt");
13         
14         // 一边读,一边写
15         byte[] arr = new byte[1024];
16         int length = 0;
17         
18         while ((length = fis.read(arr)) != -1) {
19             // 伴随着读的操作就去做写的操作
20             // 写法1
21 //            fos.write(arr);
22             // 写法2
23             fos.write(arr, 0, length);
24         }
25         
26         fos.close();
27         fis.close();
28     }
29 }
 1 package cn.temptation;
 2 
 3 import java.io.BufferedOutputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 
 7 public class Sample25 {
 8     public static void main(String[] args) throws IOException {
 9         /*
10          * 类 FilterOutputStream:此类是过滤输出流的所有类的超类。这些流位于已存在的输出流(基础 输出流)之上,它们将已存在的输出流作为其基本数据接收器,但可能直接传输数据或提供一些额外的功能。
11          * 
12          * 类 BufferedOutputStream:实现缓冲的输出流。通过设置这种输出流,应用程序就可以将各个字节写入底层输出流中,而不必针对每次字节写入调用底层系统。 
13          * 
14          * BufferedOutputStream类的构造函数:
15          * BufferedOutputStream(OutputStream out):创建一个新的缓冲输出流,以将数据写入指定的底层输出流。 
16          * BufferedOutputStream(OutputStream out, int size):创建一个新的缓冲输出流,以将具有指定缓冲区大小的数据写入指定的底层输出流。
17          * 
18          * BufferedOutputStream类的常用成员方法:
19          * 1、void write(int b) :将指定的字节写入此缓冲的输出流。
20          * 2、void flush():刷新此缓冲的输出流。迫使所有缓冲的输出字节被写出到底层输出流中。   
21          */
22         
23         FileOutputStream fos = new FileOutputStream("D:\\test01.txt");
24         BufferedOutputStream bos = new BufferedOutputStream(fos);
25         
26         // 写出数据并做强制刷新出去
27         bos.write("test".getBytes());
28         bos.flush();
29         
30         bos.close();
31         fos.close();
32     }
33 }
 1 package cn.temptation;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.FileInputStream;
 5 import java.io.IOException;
 6 
 7 public class Sample26 {
 8     public static void main(String[] args) throws IOException {
 9         /*
10          * 类 FilterInputStream:包含其他一些输入流,它将这些流用作其基本数据源,它可以直接传输数据或提供一些额外的功能。
11          * 继承自InputStream抽象类
12          * 
13          * 类BufferedInputStream:为另一个输入流添加一些功能,即缓冲输入以及支持 mark 和 reset 方法的能力。
14          * 
15          * BufferedInputStream类的构造函数:
16          * 1、BufferedInputStream(InputStream in):创建一个 BufferedInputStream 并保存其参数,即输入流 in,以便将来使用。 
17          * 2、BufferedInputStream(InputStream in, int size):创建具有指定缓冲区大小的 BufferedInputStream 并保存其参数,即输入流 in,以便将来使用。
18          * 
19          * BufferedInputStream类的常用成员方法:
20          * 1、int read():参见 InputStream 的 read 方法的常规协定。
21          * 2、int read(byte[] b, int off, int len):从此字节输入流中给定偏移量处开始将各字节读取到指定的 byte 数组中。
22          *         参数:b - 目标缓冲区。    off - 开始存储字节处的偏移量。    len - 要读取的最大字节数。
23          *         返回:读取的字节数;如果已到达流末尾,则返回 -1。  
24          */
25         
26         BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\test01.txt"));
27         
28         // 写法1、读取一个字节
29 //        int ch = 0;
30 //        
31 //        while ((ch = bis.read()) != -1) {
32 //            System.out.println((char)ch);
33 //        }
34         
35         // 写法2、读取一个字节数组(缓冲区对象)
36         byte[] arr = new byte[1024];
37         int length = 0;
38         
39         while ((length = bis.read(arr)) != -1) {
40             System.out.println(length);            // 缓冲区中读取的总字节数:4
41             System.out.println(new String(arr, 0, length));        // test
42         }
43         
44         bis.close();
45     }
46 }
  1 package cn.temptation;
  2 
  3 import java.io.BufferedInputStream;
  4 import java.io.BufferedOutputStream;
  5 import java.io.FileInputStream;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 
  9 public class Sample27 {
 10     public static void main(String[] args) throws IOException {
 11         // 比较IO操作的耗时
 12         long startTime = System.currentTimeMillis();
 13         
 14 //        method1("D:\\KuGou\\田馥甄 - 傻子.mp3", "D:\\田馥甄 - 傻子.mp3");
 15 //        method2("D:\\KuGou\\田馥甄 - 傻子.mp3", "D:\\田馥甄 - 傻子.mp3");
 16 //        method3("D:\\KuGou\\田馥甄 - 傻子.mp3", "D:\\田馥甄 - 傻子.mp3");
 17         method4("D:\\KuGou\\田馥甄 - 傻子.mp3", "D:\\田馥甄 - 傻子.mp3");
 18         
 19         long endTime = System.currentTimeMillis();
 20         
 21         System.out.println("耗时:" + (endTime - startTime));
 22         
 23         // 显然,使用缓冲区比不使用缓冲区耗时少了很多
 24         // 类比理解:古代欧洲人写字,拿着棍子一次蘸一滴墨;古代中国人写字,拿着毛笔一次蘸一管墨(容器思想)
 25     }
 26     
 27     /**
 28      * 字节流一次读写一个字节(耗时:38080)
 29      * @param src
 30      * @param target
 31      * @throws IOException 
 32      */
 33     public static void method1(String src, String target) throws IOException {
 34         FileInputStream fis = new FileInputStream(src);
 35         FileOutputStream fos = new FileOutputStream(target);
 36         
 37         int ch = 0;
 38         
 39         while ((ch = fis.read()) != -1) {
 40             fos.write(ch);
 41             fos.flush();
 42         }
 43         
 44         fos.close();
 45         fis.close();
 46     }
 47     
 48     /**
 49      * 字节流一次读写一个字节数组(字节数组作为缓冲区)(耗时:78)
 50      * @param src
 51      * @param target
 52      * @throws IOException 
 53      */
 54     public static void method2(String src, String target) throws IOException {
 55         FileInputStream fis = new FileInputStream(src);
 56         FileOutputStream fos = new FileOutputStream(target);
 57         
 58         byte[] arr = new byte[1024];
 59         int length = 0;
 60         
 61         while ((length = fis.read(arr)) != -1) {
 62             fos.write(arr, 0, length);
 63             fos.flush();
 64         }
 65         
 66         fos.close();
 67         fis.close();
 68     }
 69     
 70     /**
 71      * 缓冲字节流一次读写一个字节(耗时:23922)
 72      * @param src
 73      * @param target
 74      * @throws IOException 
 75      */
 76     public static void method3(String src, String target) throws IOException {
 77         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
 78         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target));
 79         
 80         int ch = 0;
 81         
 82         while ((ch = bis.read()) != -1) {
 83             bos.write(ch);
 84             bos.flush();
 85         }
 86         
 87         bos.close();
 88         bis.close();
 89     }
 90     
 91     /**
 92      * 缓冲字节流一次读写一个字节数组(字节数组作为缓冲区)(耗时:78)
 93      * @param src
 94      * @param target
 95      * @throws IOException 
 96      */
 97     public static void method4(String src, String target) throws IOException {
 98         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
 99         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target));
100         
101         byte[] arr = new byte[1024];
102         int length = 0;
103         
104         while ((length = bis.read(arr)) != -1) {
105             bos.write(arr, 0, length);
106             bos.flush();
107         }
108         
109         bos.close();
110         bis.close();
111     }
112 }
 1 package cn.temptation;
 2 
 3 import java.io.UnsupportedEncodingException;
 4 import java.util.Arrays;
 5 
 6 public class Sample28 {
 7     public static void main(String[] args) throws UnsupportedEncodingException {
 8         /*
 9          * 字节流操作英文数字字符很方便,但是对于非英文数字字符(比如:中文等)不够方便,所以Java中提供了字符流
10          * 
11          * 字符流  =  字节流   +  编码表(字符集)
12          * 
13          * 常见编码表(字符集):
14          * 1、ASCII:美国标准信息交换码
15          * 2、ISO8859-1:拉丁码表、欧洲码表
16          * 3、GB2312:中国的中文编码表
17          * 4、GBK:中国的中文编码表的升级
18          * 5、BIG-5:通行于香港、台湾地区的繁体字编码表
19          * 6、Unicode:国际标准码,所有的文字都使用2个字节表示
20          * 7、UTF-8:最多用3个字节表示一个字符(兼容最多的文字内容)
21          * 
22          * String字符串类的编码和解码:
23          * 编码:字符串----->字节数组
24          * 解码:字节数组----->字符串
25          * 
26          * String类的常用成员方法:
27          * 1、byte[] getBytes(Charset charset):使用给定的 charset 将此 String 编码到 byte 序列,并将结果存储到新的 byte 数组。
28          * 
29          * String类的构造函数:
30          * 1、String(byte[] bytes, Charset charset):通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String。
31          */
32         
33         String str = "中国";
34         
35         // 编码
36         byte[] arr = str.getBytes("GBK");
37         System.out.println(Arrays.toString(arr));    // [-42, -48, -71, -6]
38         
39         // 解码
40         String result = new String(arr, "GBK");
41 //        String result = new String(arr, "UTF-8");
42         System.out.println(result);                    // 中国
43         
44         // 注意:编码和解码使用相同的编码表(字符集)
45     }
46 }
 1 package cn.temptation;
 2 
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 import java.io.OutputStreamWriter;
 6 
 7 public class Sample29 {
 8     public static void main(String[] args) throws IOException {
 9         /*
10          * 类 Writer:用于写入字符流的抽象类。
11          * 
12          * Writer类的常用成员方法:
13          * 1、abstract  void close():关闭此流,但要先刷新它。 
14          * 2、abstract  void flush():刷新该流的缓冲。 
15          * 3、void write(String str):写入字符串。 
16          * 
17          * 类 OutputStreamWriter:OutputStreamWriter 是字符流通向字节流的桥梁:可使用指定的charset将要写入流中的字符编码成字节。
18          * 
19          * OutputStreamWriter类的构造函数:
20          * 1、OutputStreamWriter(OutputStream out):创建使用默认字符编码的 OutputStreamWriter。
21          * 2、OutputStreamWriter(OutputStream out, String charsetName):创建使用指定字符集的 OutputStreamWriter。
22          */
23         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:\\test01.txt"));
24         
25         osw.write("可以直接写出中文了!");
26         
27         osw.flush();
28         osw.close();
29     }
30 }
 1 package cn.temptation;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 
 7 public class Sample30 {
 8     public static void main(String[] args) throws IOException {
 9         /*
10          * 类 Reader:用于读取字符流的抽象类。
11          * 
12          * Reader类的常用成员方法:
13          * 1、abstract  void close():关闭该流并释放与之关联的所有资源。
14          * 2、int read():读取单个字符。 
15          * 
16          * 类 InputStreamReader:字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符。
17          * 
18          * InputStreamReader类的构造函数:
19          * InputStreamReader(InputStream in):创建一个使用默认字符集的 InputStreamReader。
20          * InputStreamReader(InputStream in, String charsetName):创建使用指定字符集的 InputStreamReader。
21          * 
22          * InputStreamReader类的常用成员方法:
23          * 1、int read():读取单个字符。 
24          *         返回:读取的字符,如果已到达流的末尾,则返回 -1 
25          */
26         
27         InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\test01.txt"), "UTF-8");
28         
29         int ch = 0;
30         
31         while ((ch = isr.read()) != -1) {
32             System.out.println((char)ch);
33         }
34         
35         isr.close();
36     }
37 }
 1 package cn.temptation;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.InputStreamReader;
 7 import java.io.OutputStreamWriter;
 8 
 9 public class Sample31 {
10     public static void main(String[] args) throws IOException {
11         // 需求:使用字符流实现从test01.txt读取内容,写出到test02.txt中
12         
13         InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\test01.txt"));
14         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:\\test02.txt"));
15         
16         // 写法1、一次读写一个字符
17 //        int ch = 0;
18 //        
19 //        while ((ch = isr.read()) != -1) {
20 //            osw.write(ch);
21 //            osw.flush();
22 //        }
23         
24         // 写法2
25         char[] arr = new char[1024];
26         int length = 0;
27         
28         while ((length = isr.read(arr)) != -1) {
29             osw.write(arr, 0, length);
30             osw.flush();
31         }
32         
33         osw.close();
34         isr.close();
35     }
36 }
 1 package cn.temptation;
 2 
 3 import java.io.FileReader;
 4 import java.io.FileWriter;
 5 import java.io.IOException;
 6 
 7 public class Sample32 {
 8     public static void main(String[] args) throws IOException {
 9         /*
10          * 因为InputStreamReader和OutputStreamWriter类名太长,所以Java语言提供了简化形式:FileReader和FileWriter
11          * 
12          * FileReader类:用来读取字符文件的便捷类。InputStreamReader类的子类
13          * 
14          * FileReader类的构造函数:
15          * FileReader(String fileName):在给定从中读取数据的文件名的情况下创建一个新 FileReader。
16          *
17          * 
18          * FileWriter类:用来写入字符文件的便捷类。OutputStreamWriter类的子类
19          * 
20          * FileWriter类的构造函数:
21          * FileWriter(String fileName):根据给定的文件名构造一个 FileWriter 对象。
22          */
23         
24         // 需求:使用简化字符流实现从test01.txt读取内容,写出到test02.txt中
25         FileReader reader = new FileReader("D:\\test01.txt");
26         FileWriter writer = new FileWriter("D:\\test02.txt");
27         
28         char[] arr = new char[1024];
29         int length = 0;
30         
31         while ((length = reader.read(arr)) != -1) {
32             writer.write(arr, 0, length);
33             writer.flush();
34         }
35         
36         writer.close();
37         reader.close();
38     }
39 }
 1 package cn.temptation;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.BufferedWriter;
 5 import java.io.FileReader;
 6 import java.io.FileWriter;
 7 import java.io.IOException;
 8 
 9 public class Sample33 {
10     public static void main(String[] args) throws IOException {
11         /*
12          * 类 BufferedReader:从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。 
13          * 
14          * BufferedReader类的构造函数:
15          * BufferedReader(Reader in):创建一个使用默认大小输入缓冲区的缓冲字符输入流。
16          * 
17          * 
18          * 类 BufferedWriter:将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。 
19          * 
20          * BufferedWriter类的构造函数:
21          * BufferedWriter(Writer out):创建一个使用默认大小输出缓冲区的缓冲字符输出流。
22          */
23         
24         // 需求:使用缓冲字符流实现从test01.txt读取内容,写出到test02.txt中
25         BufferedReader reader = new BufferedReader(new FileReader("D:\\test01.txt"));
26         BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\test02.txt"));
27         
28         char[] arr = new char[1024];
29         int length = 0;
30         
31         while ((length = reader.read(arr)) != -1) {
32             writer.write(arr, 0, length);
33             writer.flush();
34         }
35         
36         writer.close();
37         reader.close();
38     }
39 }
 1 package cn.temptation;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.FileReader;
 5 import java.io.IOException;
 6 import java.util.ArrayList;
 7 import java.util.Collection;
 8 import java.util.Random;
 9 
10 public class Sample34 {
11     public static void main(String[] args) throws IOException {
12         // 需求:使用IO,制作一个抽奖程序(在文本文件中存储一系列人名,实现随机抽取一个)
13         
14         // 思路:
15         // 1、从文本文件中一行一行的读取
16         // 2、读取出来的名字存储在一个内存容器中
17         // 3、随机出一个数字,对应容器中的元素
18         
19         /*
20          * BufferedReader类的常用成员方法:
21          * 1、String readLine():读取一个文本行。
22          *         返回:包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null
23          */
24         
25         // 1、从文本文件中一行一行的读取
26         BufferedReader reader = new BufferedReader(new FileReader("人员名单.txt"));
27         
28         // 2、创建一个内存容器
29         Collection<String> collection = new ArrayList<>();
30         
31         String temp = null;
32         
33         while ((temp = reader.readLine()) != null) {
34             collection.add(temp);
35         }
36         
37         reader.close();
38         
39         // 3、随机产生一个数字
40         /*
41          * 类 Random:此类的实例用于生成伪随机数流。
42          * 
43          * Random类的常用成员方法:
44          * int nextInt(int n):返回一个伪随机数,它是取自此随机数生成器序列的、在 0(包括)和指定值(不包括)之间均匀分布的 int 值。 
45          */
46         Random random = new Random();
47         int index = random.nextInt(collection.size());
48         
49         String result = ((ArrayList<String>)collection).get(index);
50         
51         System.out.println("恭喜" + result + "中奖啦!");
52     }
53 }
 1 package cn.temptation;
 2 
 3 import java.io.FileNotFoundException;
 4 import java.io.PrintWriter;
 5 
 6 public class Sample35 {
 7     public static void main(String[] args) throws FileNotFoundException {
 8         /*
 9          * 类 PrintWriter:向文本输出流打印对象的格式化表示形式。
10          * 
11          * 打印流的特点:
12          * 1、只能操作目标,不能操作源头
13          * 2、操作可以是任意类型的数据
14          * 3、可以设置自动刷新
15          * 4、可以操作文本流
16          */
17         
18         PrintWriter writer = new PrintWriter("D:\\test01.txt");
19         
20         writer.write("中国");
21         writer.write("美国");
22         writer.write("日本");
23         
24         writer.flush();
25         writer.close();
26     }
27 }
 1 package cn.temptation;
 2 
 3 import java.io.FileWriter;
 4 import java.io.IOException;
 5 import java.io.PrintWriter;
 6 
 7 public class Sample36 {
 8     public static void main(String[] args) throws IOException {
 9         /*
10          * PrintWriter类的构造函数:
11          * 1、PrintWriter(OutputStream out, boolean autoFlush):通过现有的 OutputStream 创建新的 PrintWriter。
12          *         参数:out - 输出流;autoFlush - boolean 变量;如果为 true,则 println、printf 或 format 方法将刷新输出缓冲区
13          * 
14          * PrintWriter类的常用成员方法:
15          * 1、void print(String s):打印字符串
16          * 2、void println(String x):打印 String,然后终止该行。  
17          */
18         
19         PrintWriter writer = new PrintWriter(new FileWriter("D:\\test01.txt"), true);
20         
21         writer.println("中国");
22         writer.println("美国");
23         writer.println("日本");
24         
25         writer.close();
26     }
27 }
 1 package cn.temptation;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.FileReader;
 5 import java.io.FileWriter;
 6 import java.io.IOException;
 7 import java.io.PrintWriter;
 8 
 9 public class Sample37 {
10     public static void main(String[] args) throws IOException {
11         // 需求:使用字符缓冲流  和  字符打印流  从test01.txt文件中读取内容,写出到test02.txt文件中
12         
13         BufferedReader reader = new BufferedReader(new FileReader("D:\\test01.txt"));
14         PrintWriter writer = new PrintWriter(new FileWriter("D:\\test02.txt"));
15         
16         String temp = null;
17         
18         while ((temp = reader.readLine()) != null) {
19             writer.println(temp);
20             writer.flush();
21         }
22         
23         writer.close();
24         reader.close();
25     }
26 }
 1 package cn.temptation;
 2 
 3 import java.io.PrintStream;
 4 import java.util.Scanner;
 5 
 6 public class Sample38 {
 7     public static void main(String[] args) {
 8         /*
 9          * 标准输入流:static InputStream in “标准”输入流。 
10          * 标准输出流:static PrintStream out “标准”输出流。
11          * 
12          * System类的字段:in  和    out
13          * 代表了系统标准的输入和输出设备,默认输入设备是键盘,输出设备是显示器
14          */
15         
16         Scanner input = new Scanner(System.in);
17         input.close();
18         
19         System.out.println("temptation");
20         // 上句语句等价于
21         PrintStream ps = System.out;
22         ps.println("temptation");
23     }
24 }
 1 package cn.temptation;
 2 
 3 import java.io.BufferedOutputStream;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.InputStream;
 8 import java.io.SequenceInputStream;
 9 
10 public class Sample39 {
11     public static void main(String[] args) throws IOException {
12         /*
13          * 字节混合流
14          * 类 SequenceInputStream:表示其他输入流的逻辑串联。
15          *         它从输入流的有序集合开始,并从第一个输入流开始读取,直到到达文件末尾,
16          *         接着从第二个输入流读取,依次类推,直到到达包含的最后一个输入流的文件末尾为止。
17          * 
18          * SequenceInputStream类的常用构造函数:
19          * SequenceInputStream(InputStream s1, InputStream s2):通过记住这两个参数来初始化新创建的 SequenceInputStream(将按顺序读取这两个参数,先读取 s1,然后读取 s2),以提供从此 SequenceInputStream 读取的字节。
20          */
21         
22         InputStream is1 = new FileInputStream("D:\\test01.txt");
23         InputStream is2 = new FileInputStream("D:\\test02.txt");
24         
25         SequenceInputStream sis = new SequenceInputStream(is1, is2);
26         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\test03.txt"));
27         
28         byte[] arr = new byte[1024];
29         int length = 0;
30         
31         while ((length = sis.read(arr)) != -1) {
32             bos.write(arr, 0, length);
33             bos.flush();
34         }
35         
36         bos.close();
37         sis.close();
38         is1.close();
39         is2.close();
40     }
41 }
 1 package cn.temptation;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.ObjectInputStream;
 7 import java.io.ObjectOutputStream;
 8 
 9 public class Sample40 {
10     public static void main(String[] args) throws IOException, ClassNotFoundException {
11         /*
12          * 序列化流 和 反序列化流
13          * 序列化流:把对象按照流的形式存储在资源中或在网络中传输
14          * 反序列化流:从资源中或在网络中传输把数据流还原为对象
15          * 
16          * 类 ObjectOutputStream:将Java对象的基本数据类型和图形写入 OutputStream。
17          *         可以使用 ObjectInputStream读取(重构)对象。通过在流中使用文件可以实现对象的持久存储。
18          *         如果流是网络套接字流,则可以在另一台主机上或另一个进程中重构对象。
19          * 
20          * ObjectOutputStream类的常用成员方法:
21          * void writeObject(Object obj):将指定的对象写入 ObjectOutputStream。 
22          * 
23          * 
24          * 类 ObjectInputStream:对以前使用 ObjectOutputStream写入的基本数据和对象进行反序列化。
25          * 
26          * ObjectInputStream类的常用成员方法:
27          * Object readObject():从 ObjectInputStream 读取对象。 
28          * 
29          * 接口 Serializable:类通过实现 java.io.Serializable 接口以启用其序列化功能。未实现此接口的类将无法使其任何状态序列化或反序列化。
30          *         可序列化类的所有子类型本身都是可序列化的。序列化接口没有方法或字段,仅用于标识可序列化的语义。
31          * 
32          */
33         
34 //        write();
35         read();
36     }
37     
38     /**
39      * 序列化对象
40      * @throws IOException 
41      */
42     public static void write() throws IOException {
43         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\student.txt"));
44         
45         oos.writeObject(new Student("张三", 18));
46         
47         oos.flush();
48         
49         oos.close();
50     }
51     
52     /**
53      * 反序列化对象
54      * @throws IOException 
55      * @throws ClassNotFoundException 
56      */
57     public static void read() throws IOException, ClassNotFoundException {
58         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\student.txt"));
59         
60         Object object = ois.readObject();
61         
62         ois.close();
63         
64         System.out.println(object);
65         System.out.println("姓名为:" + ((Student)object).getStudentName() + ",年龄为:" + ((Student)object).getStudentAge());
66     }
67 }
 1 package cn.temptation;
 2 
 3 import java.io.Serializable;
 4 
 5 // 下句执行异常:java.io.NotSerializableException: cn.temptation.Student,因为没有实现Serializable接口
 6 //public class Student {
 7 public class Student implements Serializable {
 8     private static final long serialVersionUID = 1L;
 9     
10     // 成员变量
11     private String studentName;
12     private Integer studentAge;
13 
14     // 构造函数
15     public Student() {
16         super();
17     }
18 
19     public Student(String studentName, Integer studentAge) {
20         super();
21         this.studentName = studentName;
22         this.studentAge = studentAge;
23     }
24 
25     // 成员方法
26     public String getStudentName() {
27         return studentName;
28     }
29 
30     public void setStudentName(String studentName) {
31         this.studentName = studentName;
32     }
33 
34     public Integer getStudentAge() {
35         return studentAge;
36     }
37 
38     public void setStudentAge(Integer studentAge) {
39         this.studentAge = studentAge;
40     }
41 
42 }

猜你喜欢

转载自www.cnblogs.com/iflytek/p/9451015.html