字符流详解及代码测试

1:字符流

(1)字节流操作中文数据不是特别的方便,所以就出现了转换流。

    这里在复制文件时是不会出现问题的,从一个文件读到另一个文件显示不会出错,但是要读文件显示控制台就会出现无法读到中文的错误

看下面的例子:

 1 /*
 2  * 字节流读取中文可能出现的问题
 3  */
 4 public class FileInputStreamDemo {
 5 
 6     public static void main(String[] args) throws IOException {
 7         //创建字节输入流对象
 8         FileInputStream fis = new FileInputStream("a.txt");
 9         //读取数据
10         int by = 0;
11         while((by = fis.read()) != -1){
12             //System.out.print(by);//104101108108111
13             System.out.print((char) by);//hello    //hello???ú
14         }
15         
16 //        byte[] bys = new byte[1024];
17 //        int len = 0;
18 //        while((len = fis.read(bys)) != -1){
19 //            System.out.print(new String(bys, 0, len));//hello中国
20 //        
21 //        }
22         
23         //释放资源
24         fis.close();
25     }
26     
27 }

     转换流的作用就是把字节流转换字符流来使用。
     转换流其实是一个字符流
     字符流 = 字节流 + 编码表


(3)编码表
    A:就是由字符和对应的数值组成的一张表
    B:常见的编码表
        ASCII
       ISO-8859-1
  GB2312
  GBK
  GB18030
  UTF-8
   C:字符串中的编码问题

      String(byte[] bytes, String charsetName):通过指定的字符集解码字节数组

      byte[]  getBytes (String charsetName):使用指定的字符集合把字符串编码为字节数组

     编码:把可以看得懂的变成看不懂的
     String -- byte[]
     解码:把看不懂的变成看得懂的
     byte[] -- String

 1 public class StringDemo {
 2     public static void main(String[] args) {
 3         String s = "你好吗?";
 4         
 5         //String----byte[]
 6         byte[] bys = s.getBytes();
 7         System.out.println(Arrays.toString(bys));//[-28, -67, -96, -27, -91, -67, -27, -112, -105, -17, -68, -97]
 8 
 9         //byte[]----String
10         String ss = new String(bys);
11         System.out.println(ss);//你好吗?
12     }
13 
14 }

      切记编码和解码的格式要一直!!!!!


(4)IO流中的编码问题
A:OutputStreamWriter

     字符流 = 字节流 + 编码表
    OutputStreamWriter(OutputStream os):默认编码,GBK
    OutputStreamWriter(OutputStream os,String charsetName):指定编码。

 1 public class OutputStringWriterDemo {
 2     public static void main(String[] args) throws IOException {
 3         //创建对象
 4         //OutputStreamWriter osw = new OutputStreamWriter(
 5                 //new FileOutputStream("a.txt"));//默认GBK
 6         OutputStreamWriter osw = new OutputStreamWriter(
 7                 new FileOutputStream("a.txt"), "GBK");//指定GBK
 8         
 9         //OutputStreamWriter osw = new OutputStreamWriter(
10                 //new FileOutputStream("a.txt"), "UTF-8");//指定UTF-8
11         //写数据
12         osw.write("你好!");
13         
14         //释放资源
15         osw.close();
16     }
17 
18 }


B:InputStreamReader
    InputStreamReader(InputStream is):默认编码,GBK
    InputStreamReader(InputStream is,String charsetName):指定编码

 1 public class InputStreamReaderDemo {
 2 
 3     public static void main(String[] args) throws IOException {
 4         //创建对象
 5         InputStreamReader isr = new InputStreamReader(
 6                 new FileInputStream("a.txt"));
 7         //InputStreamReader isr = new InputStreamReader(
 8                 //new FileInputStream("a.txt"), "GBK");
 9         //读取数据
10         //一次读一个字节
11         int ch = 0;
12         while((ch = isr.read()) != -1){
13             System.out.println((char)ch);
14         }
15         //释放资源
16         isr.close();
17         
18     }
19 }

保证编码一致。


C:编码问题其实很简单
编码只要一致即可


(5)字符流
Reader
|--InputStreamReader  转换流

 1 /*
 2  * InputStreamReader
 3  * int read() 一次读一个字符
 4  * int read(char[] ch)一次读一个字符数组
 5  */
 6 public class InputStreamReaderDemo2 {
 7 
 8     public static void main(String[] args) throws IOException {
 9         //创建对象
10         InputStreamReader isr = new InputStreamReader(new 
11                 FileInputStream("a.txt"));
12         // int read() 一次读一个字符
13         int ch = 0;
14         while((ch = isr.read()) != -1){
15             System.out.println((char)ch);
16         }
17         
18         //int read(char[] ch)一次读一个字符数组
19         char[] chs = new char[1024];
20         int len = 0;
21         while((len = isr.read(chs)) != -1){
22             System.out.println(new String(chs, 0, len));
23         }
24     }
25 }


|--FileReader

我们一般操作都是基于本地默认的编码表,因此不用特意指定编码

由于转换流的名字比较长,所以java就提供了他的子类供使用

InputStreamReader = FileIntputStream + 编码表(GBK)

FileReader= FileIntputStream + 编码表(GBK)

 1 /*
 2  * 数据源:
 3  *     a.txt   读取数据      字符转换流     InputStreamReader   FileReader
 4  * 目的地:
 5  *     b.txt   写出数据      字符转换流      OutputStreamWriter   FileWriter
 6  */
 7 public class CopyFileDemo {
 8     public static void main(String[] args) throws IOException {
 9         //封装数据源
10         FileReader fr = new FileReader("a.txt");
11         //封装目的地
12         FileWriter fw = new FileWriter("b.txt");
13         
14         //一次读一个字符
15         int ch = 0;
16         while((ch = fr.read()) != -1){
17             fw.write(ch);
18         }
19         
20         //一次读一个字符数组
21         char[] chs = new char[1024];
22         int len = 0;
23         while((len = fr.read(chs)) != -1){
24             fw.write(chs, 0, len);
25             fw.flush();
26         }
27         
28         //释放资源
29         fw.close();
30         fr.close();
31     }
32 
33 }


|--BufferedReader  字符缓冲流

 1 //BufferedReader 从字符输入流中读取文本,缓冲各个字符,从而实现字符  数组  和行的高效读取
 2 public class BufferedReaderDemo {
 3 
 4     public static void main(String[] args) throws IOException {
 5         //创建字符缓冲输入流对象
 6     
 7         BufferedReader br = new BufferedReader(new FileReader("a.txt"));
 8         
 9         //一次读取一个字符
10         //int ch = 0;
11         //while((ch = br.read()) != -1){
12             //System.out.println((char) ch);
13         //}
14         
15         //一次读取一个字符数组
16         char[] chs = new char[1024];
17         int len = 0;
18         while((len = br.read(chs)) != -1){
19             System.out.println(new String(chs, 0, len));
20         }
21         
22         //释放资源
23         br.close();
24     }
25 }


Writer
|--OutputStreamWriter

 1 /*
 2  * OutputStreamWriter方法:
 3  * public void write(int c) 写一个字符
 4  * public void write(char[] cbuf) 写一个字符数组
 5  * public void write(char[] cbuf, int off, int len) 写一个字符数组的一部分
 6  * public void write(String str) 写一个字符串
 7  * public void write(String str, int off, int len) 写一个字符串的一部分
 8  */
 9 public class OutputStreamWriterDemo {
10     public static void main(String[] args) throws IOException {
11         //创建对象
12         OutputStreamWriter osw = new OutputStreamWriter(
13                 new FileOutputStream("a.txt")); 
14         //写数据
15         //public void write(int c) 写一个字符
16         osw.write('a');
17         osw.write(97);
18         /*
19          * 运行会发现没有数据写进去,原因是字符=2字节
20          * 文件中数据存储的基本单位是字节啊
21          * 这时要void flush()
22          */
23         
24         //public void write(char[] cbuf) 写一个字符数组
25         char[] ch = {'a', 'b', 'c', 'd', 'e'};
26         osw.write(ch);
27         
28         //public void write(char[] cbuf, int off, int len) 写一个字符数组的一部分
29         osw.write(ch, 1, 3);
30         
31         //public void write(String str) 写一个字符串
32         osw.write("我爱中国");
33         
34         //public void write(String str, int off, int len) 写一个字符串的一部分
35         osw.write("我爱中国", 2, 2);
36         
37         //刷新缓冲区
38         osw.flush();
39         
40         //释放资源   
41         osw.close();
42         
43         /*
44          * close()关闭流对象,在此之前先刷新一次缓冲区,关闭之后流对象就不能继续使用了
45          * flush()只是刷新缓冲区,刷新之后流对象照样可以使用
46          * 一般用close就可以了,数据量不是很大
47          * 因为每写一次调用一次flush方法这样会增加开销
48          */
49     }
50 
51 }

|--FileWriter

OutputStreamWriter = FileOutputStream + 编码表(GBK)

FileWriter = FileOutputStream + 编码表(GBK)


|--BufferedWriter 字符缓冲流

 1 /*
 2  * 字符流为了高效的读写因此也给提供了字符缓冲流
 3  * BufferedWriter  字符缓冲输出流
 4  * BufferedWriter  字符缓冲输入流
 5  */
 6 public class BufferedWriterDemo {
 7 
 8     public static void main(String[] args) throws IOException {
 9         //BufferedWriter(Writer out)
10         //BufferedWriter bw = new BufferedWriter(new 
11                 //OutputStreamWriter(new FileOutputStream("a.txt")));
12         
13         BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
14         
15         bw.write("hello");
16         bw.write("word");
17         bw.write("java");
18         
19         bw.close();
20     }
21 }


(6)复制文本文件(5种方式)

 1 /*
 2  * 将当前项目先的a.txt文件内容复制到当前项目下的b.txt wenj 
 3  * 
 4  * 数据源:
 5  *     a.txt   读取数据        字符转换流    InputStreamReader
 6  * 目的地
 7  *     b.txt   写出数据       字符转换流    OutputStreamWriter
 8  */
 9 public class CopyFile1 {
10 
11     public static void main(String[] args) throws IOException {
12         //封装数据源
13         InputStreamReader isr = new InputStreamReader(
14                 new FileInputStream("a.txt"));
15         //封装目的地
16         OutputStreamWriter osw = new OutputStreamWriter(
17                 new FileOutputStream("b.txt"));
18         
19         //写数据
20         //一次一个字符
21         //int ch = 0;
22         //while((ch = isr.read()) != -1){
23             //osw.write(ch);
24             
25         //}
26         
27         //一次写一个字符数组
28         char[] chs = new char[1024];
29         int len = 0;
30         while((len = isr.read(chs)) != -1){
31             osw.write(chs, 0, len);
32             //osw.flush()//可以不flush 小文件
33         }
34         
35         
36         //释放资源
37         osw.close();
38         isr.close();
39     }
40 }
 1 /*
 2  * 将e盘下的a.txt 文件复制到e盘下的b.txt
 3  * 
 4  * 数据源:
 5  *    e:\a.txt    FileReader
 6  * 目的地:
 7  *    e:\b.txt    FileWriter
 8  *     
 9  */
10 public class CopyFileDemo2 {
11 
12     public static void main(String[] args) throws IOException {
13         //封装数据源
14         FileReader fr = new FileReader("e://a.txt");
15         //封装目的地
16         FileWriter fw = new FileWriter("e://b.txt");
17         
18         //读写数据  一次一个字符
19         //int ch = 0;
20         //int ch;
21         //while((ch = fr.read()) != -1){
22             //fw.write(ch);
23         //}
24         
25         //一次读取一个字符数组
26         char[] ch = new char[1024];
27         int len = 0;
28         while((len = fr.read(ch)) != -1){
29             fw.write(ch, 0, len);
30         }
31         
32         //释放资源
33         fw.close();
34         fr.close();
35     }
36 }
 1 public class CopyFiledemo3 {
 2     public static void main(String[] args) throws IOException {
 3         //封装数据源
 4         BufferedReader br = new BufferedReader(new FileReader("a.txt"));
 5         //封装目的地
 6         BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));
 7         
 8         //两种方法其中的一种  一次读取一个字符数组
 9         char[] ch = new char[1024];
10         int len = 0;
11         while((len = br.read()) != -1){
12             bw.write(ch, 0, len);
13             bw.flush();
14             
15         }
16         //释放资源
17         bw.close();
18         br.close();
19     }
20 
21 }

 高效写法

 1 public class CopyFileDemo4 {
 2     public static void main(String[] args) throws IOException {
 3         //封装数据源
 4         BufferedReader br = new BufferedReader(new FileReader("a.txt"));
 5         //封装目的地
 6         BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));
 7         
 8         //读写数据
 9         String line = null;
10         while((line = br.readLine()) != null){
11             bw.write(line);
12             bw.newLine();
13             bw.flush();
14         }
15         //释放资源
16         bw.close();
17         br.close();
18     }
19 
20 }

2:IO流小结(掌握)
IO流
|--字节流
|--字节输入流
InputStream
int read():一次读取一个字节
int read(byte[] bys):一次读取一个字节数组

|--FileInputStream
|--BufferedInputStream
|--字节输出流
OutputStream
void write(int by):一次写一个字节
void write(byte[] bys,int index,int len):一次写一个字节数组的一部分

|--FileOutputStream
|--BufferedOutputStream
|--字符流
|--字符输入流
Reader
int read():一次读取一个字符
int read(char[] chs):一次读取一个字符数组

|--InputStreamReader
|--FileReader
|--BufferedReader
String readLine():一次读取一个字符串

 1 /*
 2  *字符 缓冲流的特殊方法
 3  *BufferedWriter
 4  *     public void newLine()根据系统决定换行
 5  *BufferedReader
 6  *     public void readLine()一次读取一行数据
 7  *     包含该行内容的字符串,不包含任何终止符,如果已达到末尾则返回null
 8  */
 9 public class BufferedDemo {
10 
11     public static void main(String[] args) throws IOException {
12         read();
13         //write();
14 
15     }
16 
17        private static void read() throws IOException {
18            BufferedReader br = new BufferedReader(new FileReader("b.txt"));
19            String line = null;
20            while((line = br.readLine()) != null){
21                System.out.println(line);
22            }
23         
24         //释放资源
25            br.close();
26     }
27 
28         //创建字符缓冲输出流对象
29         private static void write() throws IOException {
30             BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
31             for (int x = 0; x < 10; x++){
32                 bw.write("word" + x);
33                 //bw.write("
");//windows下的换行
34                 bw.newLine();
35                 bw.flush();
36             }
37             bw.close();
38         }
39         
40     }


|--字符输出流
Writer
void write(int ch):一次写一个字符
void write(char[] chs,int index,int len):一次写一个字符数组的一部分

|--OutputStreamWriter
|--FileWriter
|--BufferedWriter
void newLine():写一个换行符

 1 /*
 2  *字符 缓冲流的特殊方法
 3  *BufferedWriter
 4  *     public void newLine()根据系统决定换行
 5  *BufferedReader
 6  *     public void readLine()一次读取一行数据
 7  */
 8 public class BufferedDemo {
 9 
10     public static void main(String[] args) throws IOException {
11         //创建字符缓冲输出流对象
12         BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
13         for (int x = 0; x < 10; x++){
14             bw.write("word" + x);
15             //bw.write("
");//windows下的换行
16             bw.newLine();
17             bw.flush();
18         }
19         bw.close();
20     }


void write(String line):一次写一个字符串

3:案例
A:复制文本文件 5种方式,推荐使用第五种

  1 /*
  2  * 复制文本文件
  3  * 能用记事本打开就用字符流
  4  * 五种方式,推荐使用第五种
  5  * 
  6  * 数据源:
  7  *     e:\a.txt   FileReader   BufferedReader
  8  * 目的地:
  9  *     e:\b.txt   FileWriter   BufferedWriter
 10  * 
 11  */
 12 public class CopyFileDemo {
 13 
 14     public static void main(String[] args) throws IOException {
 15         String srcString = " e:\a.txt";
 16         String desString = " e:\b.txt";
 17         
 18         //method1(srcString, desString);
 19         //method2(srcString, desString);
 20         //method3(srcString, desString);
 21         //method4(srcString, desString);
 22         method5(srcString, desString);
 23     }
 24 
 25     //基本字符流一次读写一个字符
 26     private static void method1(String srcString, String desString) throws IOException {
 27         FileReader fr = new FileReader(srcString);
 28         FileWriter fw = new FileWriter(desString); 
 29         
 30         int ch = 0;
 31         while((ch = fr.read()) != -1){
 32             fw.write(ch);
 33         }
 34         
 35         fw.close();
 36         fr.close();
 37     }
 38     
 39     //基本字符流一次读写一个字符数组
 40     private static void method2(String srcString, String desString) throws IOException {
 41         FileReader fr = new FileReader(srcString);
 42         FileWriter fw = new FileWriter(desString); 
 43         
 44         char[] chs = new char[1024];
 45         int len = 0;
 46         while((len = fr.read(chs)) != -1){
 47             fw.write(chs, 0, len);
 48         }
 49         
 50         fw.close();
 51         fr.close();
 52     }  
 53     
 54     //字符缓冲流一次读写一个字符
 55         private static void method3(String srcString, String desString) throws IOException {
 56             BufferedReader br = new BufferedReader(new FileReader(srcString));
 57             
 58             BufferedWriter bw = new BufferedWriter(new FileWriter(desString)); 
 59             
 60             int ch = 0;
 61             while((ch = br.read()) != -1){
 62                 bw.write(ch);
 63             }
 64             
 65             bw.close();
 66             br.close();
 67         }
 68         
 69         //字符缓冲流一次读写一个字符数组
 70         private static void method4(String srcString, String desString) throws IOException {
 71             BufferedReader br = new BufferedReader(new FileReader(srcString));
 72             
 73             BufferedWriter bw = new BufferedWriter(new FileWriter(desString)); 
 74             
 75             char[] chs = new char[1024];
 76             int len = 0;
 77             while((len = br.read(chs)) != -1){
 78                 bw.write(chs, 0, len);
 79             }
 80             
 81             bw.close();
 82             br.close();
 83         }
 84         
 85         //字符缓冲流一次读写一个字符串
 86         private static void method5(String srcString, String desString) throws IOException {
 87             BufferedReader br = new BufferedReader(new FileReader(srcString));
 88             
 89             BufferedWriter bw = new BufferedWriter(new FileWriter(desString)); 
 90             
 91             String line = null;
 92             while((line = br.readLine()) != null){
 93                 bw.write(line);
 94                 bw.newLine();
 95                 bw.flush();
 96             }
 97             
 98             bw.close();
 99             br.close();
100         }
101 }


B:复制图片(二进制流数据) 4种方式(掌握)

 1 /*
 2  * 复制图片
 3  * 
 4  * 复制数据时如果我们了解能用记事本打开并可以读懂就用字符流,否则采用字节流
 5  * 因此 这里复制图片采用字节流
 6  * 字节流有4种方式,推荐掌握第四种
 7  * 
 8  * 数据源:e:\a.jpg   FileInputStream   BufferedInputStream
 9  * 目的地:e:\b.jpg   FileOutputStream  BufferedOutputStream
10  */
11 public class CopyImageDemo {
12 
13     public static void main(String[] args) throws IOException {
14         //使用字符串作为路径
15         //String srcString = "e:\a.jpg";
16         //String destString = "e:\b.jpg";
17         //这个例子这里采用File对象也可以作为参数   两种方式都可以  一般使用字符串作为参数
18         File srcFile = new File("e:\a.jpg");
19         File destFile = new File("e:\b.jpg");
20         
21         method1(srcFile, destFile);
22         //method2();
23         //method3();
24         //method4();
25         
26     }
27 
28     //基本字节流一次读写一个字节
29     private static void method1(File srcFile, File destFile) throws IOException {
30         FileInputStream fis = new FileInputStream(srcFile);
31         FileOutputStream fos = new FileOutputStream(destFile);
32         
33         int by = 0;
34         while((by = fis.read()) != -1){
35             fos.write(by);
36         }
37         fos.close();
38         fis.close();
39     }
40 
41     //基本字节流一次读写一个字节数组
42     private static void method2(File srcFile, File destFile) throws IOException {
43         FileInputStream fis = new FileInputStream(srcFile);
44         FileOutputStream fos = new FileOutputStream(destFile);
45             
46         byte[] bys = new byte[1024];
47         int len = 0;
48         while((len = fis.read(bys)) != -1){
49             fos.write(bys);
50         }
51         fos.close();
52         fis.close();
53     }
54     
55     //字节缓冲流一次读写一个字节
56     private static void method3(File srcFile, File destFile) throws IOException {
57         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
58         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
59             
60         int by = 0;
61         while((by = bis.read()) != -1){
62             bos.write(by);
63         }
64         bos.close();
65         bis.close();
66     }
67 
68     
69     //字节缓冲流一次读写一个字节数组
70         private static void method4(File srcFile, File destFile) throws IOException {
71             BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
72             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile));
73                 
74             byte[] bys = new byte[1024];
75             int len = 0;
76             while((len = bis.read(bys)) != -1){
77                 bos.write(bys);
78             }
79             bos.close();
80             bis.close();
81         }
82 }


C:把集合中的数据存储到文本文件

 1 /*
 2  * 将ArrayList集合中的字符串数据存储到文件文件
 3  * 由于ArrayList集合中存储的是字符串
 4  * 遍历ArrayList集合,将数据获取到
 5  * 存储到文本文件,文件文件可以使用字符流
 6  * 
 7  * 数据源:ArrayList<String>   遍历得到每一个字符串数据
 8  * 目的地:a.txt  FileWriter   BufferedWriter
 9  * 
10  */
11 public class ArrayListToFile {
12 
13     public static void main(String[] args) throws IOException {
14         //创建集合数据  封装数据源
15         ArrayList<String> array = new ArrayList<String>();
16         array.add("hello");
17         array.add("world");
18         array.add("demo");
19         
20         //封装目的地
21         BufferedWriter bw = new BufferedWriter(new FileWriter("a.txt"));
22         
23         //遍历集合
24         for(String s : array){
25             //写数据
26             bw.write(s);
27             bw.newLine();
28             bw.flush();
29         }
30         //释放资源
31         bw.close();
32     }
33 }


D:把文本文件中的数据读取到集合并遍历集合

 1 /*
 2  * 把文本文件中的数据读取到集合并遍历集合
 3  * 数据源是文本文件
 4  * 目的地是集合
 5  * 元素是字符串
 6  * 
 7  * 数据源:b.txt   FileReader   BufferedReader
 8  * 目的地 :ArrayList<String>
 9  */
10 public class FileToArrayListDemo {
11     public static void main(String[] args) throws IOException {
12         //封装数据源
13         BufferedReader br = new BufferedReader(new FileReader("a.txt"));
14         //封装目的地  创建集合对象
15         ArrayList<String> array = new ArrayList<String>();
16         
17         //读数据并存储到集合
18         String line = null;
19         while((line = br.readLine()) != null){
20             array.add(line);
21         }
22         //释放资源
23         br.close();
24         
25         //遍历集合
26         for(String s : array){
27             System.out.println(s);
28         }
29     }
30 
31 }

选取幸运者

 1 /*
 2  * 文本文件中存有一些人名,程序实现随机获取一个人名字
 3  * 
 4  * 把文本文件中的数据存储到集合中
 5  * 随机产生一个索引
 6  * 根据该索引获取一个值
 7  */
 8 public class GetNameDemo {
 9 
10     public static void main(String[] args) throws IOException {
11         //把文本文件中的数据存储到集合中
12         BufferedReader br = new BufferedReader(new FileReader("a.txt"));
13         ArrayList<String> array = new ArrayList<String>();
14         String line = null;
15         while((line = br.readLine()) != null){
16             array.add(line);
17         }
18         br.close();
19         
20         //随机产生一个索引
21         Random r = new Random();
22         int index = r.nextInt(array.size());
23         
24         //根据该索引获取一个值
25         String name = array.get(index);
26         System.out.println("选中的人是:" + name);
27     }
28 }


E:复制单级文件夹

 1 /*
 2  * 复制单级文件夹
 3  * 
 4  * 数据源:e:\java
 5  * 目的地:e:\test
 6  * 
 7  * 封装目录
 8  * 获取该目录下的所有文本的File数组
 9  * 遍历该File数组得到每个File对象
10  * 把该 File对象进行复制
11  * 
12  */
13 public class CopyFolder {
14 
15     public static void main(String[] args) throws IOException {
16         //封装目录
17         File srcFolfer = new File("e:\java");
18         //封装目的地
19         File destFolder = new File("e:\test");
20     
21         //由于这里是文件夹,不像是文件,系统不能自动创建,索要要先判断是否存在,如果不存在就进行创建
22         if(!destFolder.exists()){
23             destFolder.mkdir();
24         }
25         
26         //获取该目录下的所有文本的File数组
27         File[] fileArray = srcFolfer.listFiles();
28         
29         //遍历该File数组得到每个File对象
30         for (File file : fileArray){
31             System.out.println(file);
32             //先打印输出观察到  数据源:e:\java\a.mp3
33             //我们的目的地是e:\test\a.mp3  这里需要做的是后面的文件名不变  可以和目的地前半部分拼接
34     
35             //拼接目标路径
36             String name = file.getName();//a.mp3
37             File newFile = new File(destFolder, name);//e:\test\a.mp3  File的第三种方式  前面是一个路径   后面是文件名
38             
39             //写一个方法来复制   把该 File对象进行复制
40             copyFile(file, newFile);
41         }
42     }
43 
44     private static void copyFile(File file, File newFile) throws IOException {
45         BufferedInputStream bis = new BufferedInputStream(
46                 new FileInputStream(file));
47         
48         BufferedOutputStream bos = new BufferedOutputStream(
49                 new FileOutputStream(newFile));
50         
51         byte[] bys = new byte[1024];
52         int len = 0;
53         while((len = bis.read(bys)) != -1){
54             bos.write(bys, 0, len);
55         }
56         
57         bos.close();
58         bis.close();
59     }
60 
61 
62 }


F:复制单级文件夹中指定的文件并修改名称

 1 /*
 2  * 复制指定目录下的指定文件并修改文件名
 3  * 
 4  * 指定的文件是:.java文件
 5  * 指定的后缀名是.jav
 6  * 指定的目录是:jav
 7  * 
 8  * 数据源:e:\java\B.java
 9  * 目的地:e:\jav\C.jav
10  * 
11  * 封装目录
12  * 获取该目录下的java文件的File数组
13  * 遍历该File数组得到每个File对象
14  * 把该 File对象进行复制
15  * 在目的地目录下改名
16  */
17 public class CopyFolderDemo {
18 
19     public static void main(String[] args) throws IOException {
20         //封装目录
21         File srcFolder = new File("e:\java");
22         //封装目的地
23         File destFolder = new File("e:\jav");
24         //如果目录不存在就创建
25         if(! destFolder.exists()){
26             destFolder.mkdir();
27         }
28         
29         //获取该目录下的java文件的File数组
30         File[] fileArray = srcFolder.listFiles(new FilenameFilter() {
31             
32             @Override
33             public boolean accept(File dir, String name) {
34                 
35                 return new File(dir, name).isFile() && name.endsWith("java");
36             }
37         });
38         
39         //遍历该File数组得到每个File对象
40         for (File file : fileArray){
41             String name = file.getName();
42             File newFile = new File(destFolder, name);
43             
44             ////把该 File对象进行复制
45             copyFile(file, newFile);
46         }
47         
48         //在目的地目录下改名
49         File[] destFileArray = destFolder.listFiles();
50         for(File destFile : destFileArray){
51             String name = destFile.getName();
52             String newName = name.replace(".java", ".jav");
53         
54             File newFile = new File(destFolder, newName);
55             destFile.renameTo(newFile);
56         }
57     }
58     
59     
60      
61     //把该 File对象进行复制
62     private static void copyFile(File file, File newFile) throws IOException {
63         BufferedInputStream bis = new BufferedInputStream(
64                 new FileInputStream(file));
65         
66         BufferedOutputStream bos = new BufferedOutputStream(
67                 new FileOutputStream(newFile));
68         
69         byte[] bys = new byte[1024];
70         int len = 0;
71         while((len = bis.read(bys)) != -1){
72             bos.write(bys, 0, len);
73         }
74         
75         bos.close();
76         bis.close();
77     }
78 }

回顾一下批量修改名称


G:复制多级文件夹

 1 /*
 2  * 复制多级文件夹
 3  * 
 4  * 数据源:e:CodeMyCodedemo
 5  * 目的地:e:
 6  * 
 7  * A:封装数据源File
 8  * B:封装目的地File
 9  * C:判断该File是文件还是文件夹
10  *    是文件夹
11  *       就在该目的地目录下创建该文件夹
12  *       获取该File对象下的所有文件或者文件夹File对象
13  *       遍历得到每一个File对象
14  *       返回C
15  *    是文件
16  *       复制(采用字节流)
17  * 
18  */
19 public class CopyFoldersDemo {
20 
21     public static void main(String[] args) throws IOException {
22         //封装数据源File
23         File srcFile = new File("e:\Code\MyCode\demo");
24         //封装目的地File
25         File destFile = new File("e:\");
26         
27         //实现复制文件夹功能
28         copyFolder(srcFile, destFile);
29     }
30 
31     private static void copyFolder(File srcFile, File destFile) throws IOException {
32         //判断该File是文件还是文件夹
33         if(srcFile.isDirectory()){
34             //文件夹
35             File newFolder = new File(destFile, srcFile.getName());
36             newFolder.mkdir();//拿到的是文件夹就先创建文件夹
37             
38             //获取该File对象下的所有文件或者文件夹File对象
39             File[] fileArray = srcFile.listFiles();
40             for(File file : fileArray){
41                 copyFolder(file, newFolder);//做递归再一次判断
42             }
43         }else{
44             //文件
45             File newFile = new File(destFile, srcFile.getName());
46             copyFile(srcFile, newFile);//直接复制
47     }
48 }
49 
50     private static void copyFile(File srcFile, File newFile) throws IOException {
51         BufferedInputStream bis = new BufferedInputStream(
52                 new FileInputStream(srcFile));
53         
54         BufferedOutputStream bos = new BufferedOutputStream(
55                 new FileOutputStream(newFile));
56         
57         byte[] bys = new byte[1024];
58         int len = 0;
59         while((len = bis.read(bys)) != -1){
60             bos.write(bys, 0, len);
61         }
62         
63         bos.close();
64         bis.close();
65     }
66         
67     }


H:键盘录入学生信息按照总分从高到低存储到文本文件

 1 /*
 2  * 键盘录入5个学生信息(姓名  语文成绩  数学成绩 英语成绩)按照总分从高到低存入文本文件
 3  * 
 4  * 创建学生类
 5  * 创建集合对象  TreeSet<Student>
 6  * 键盘录入学生信息存储到集合
 7  * 遍历集合将数据写入文本文件
 8  */
 9 public class StudentDemo {
10     public static void main(String[] args) throws IOException {
11         //创建集合对象  TreeSet<Student>
12         TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
13 
14             @Override
15             public int compare(Student s1, Student s2) {
16             
17                 int num = s2.getSum() - s1.getSum();
18                 int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;
19                 int num3 = num2 == 0? s1.getMath() - s2.getMath() : num2;
20                 int num4 = num3 == 0? s1.getEnglish() - s2.getEnglish() : num3;
21                 int num5 = num4 == 0? s1.getName().compareTo(s2.getName()) : num4;
22                 
23                 return num5;
24                 
25             }
26         });
27         
28         //键盘录入学生信息存储到集合
29         for(int x = 1; x <= 5; x++){
30             Scanner sc = new Scanner(System.in);
31             System.out.println("请录入第:" + x + "学生的信息");
32             System.out.println("姓名:");
33             String name = sc.nextLine();
34             System.out.println("语文成绩:");
35             int chinese = sc.nextInt();
36             System.out.println("数学成绩:");
37             int math = sc.nextInt();
38             System.out.println("英语成绩:");
39             int english = sc.nextInt();
40             
41             //创建学生对象
42             Student s = new Student();
43             s.setName(name);
44             s.setChinese(chinese);
45             s.setMath(math);
46             s.setEnglish(english);
47             
48             //将学生信息添加到集合
49             ts.add(s);
50         }
51         
52         //遍历集合 将数据写到文本文件
53         BufferedWriter bw = new BufferedWriter(new FileWriter("Students"));
54         bw.write("学生信息如下:");
55         bw.newLine();
56         bw.flush();
57         bw.write("姓名,语文成绩,数学成绩,英语成绩");
58         bw.newLine();
59         bw.flush();
60         for(Student s : ts){
61             StringBuffer sb = new StringBuffer();
62             sb.append(s.getName()).append(",").append(s.getChinese())
63                .append(",").append(s.getMath())
64                .append(",").append(s.getEnglish());
65             bw.write(sb.toString());
66             bw.newLine();
67             bw.flush();
68         }
69         //释放资源
70         bw.close();
71         System.out.println("学生信息输入完毕");
72     
73     }
74 
75 }
 1 public class Student {
 2     //姓名
 3     private String name;
 4     //语文成绩
 5     private int chinese;
 6     //数学成绩
 7     private int math;
 8     //英语成绩
 9     private int english;
10     
11     public Student(){
12         super();
13     }
14     
15     public Student(String name, int chinese, int math, int english) {
16         super();
17         this.name = name;
18         this.chinese = chinese;
19         this.math = math;
20         this.english = english;
21     }
22 
23     public String getName() {
24         return name;
25     }
26 
27     public void setName(String name) {
28         this.name = name;
29     }
30 
31     public int getChinese() {
32         return chinese;
33     }
34 
35     public void setChinese(int chinese) {
36         this.chinese = chinese;
37     }
38 
39     public int getMath() {
40         return math;
41     }
42 
43     public void setMath(int math) {
44         this.math = math;
45     }
46 
47     public int getEnglish() {
48         return english;
49     }
50 
51     public void setEnglish(int english) {
52         this.english = english;
53     }
54     
55     
56     public int getSum(){
57         return this.chinese + this.math + this.english;
58     }
59 
60 }


I:把某个文件中的字符串排序后输出到另一个文本文件中

 1 /*
 2  * 将a.txt中的字符串"jdfkohbobnbbvvbicsioghobljvbnzbji"排序后写入b.txt
 3  * 
 4  * 将a.txt创建出
 5  * 读取该文件的内容存储到一个字符串中
 6  * 将字符串转换为字符数组
 7  * 对字符数组排序
 8  * 将排序后的字符数组转换为字符串
 9  * 将转换过来的字符串再次写入b.txt
10  * 
11  */
12 public class StringDemo2 {
13     public static void main(String[] args) throws IOException {
14     
15         BufferedReader br = new BufferedReader(new FileReader("a.txt"));
16         BufferedWriter bw = new BufferedWriter(new FileWriter("b.txt"));
17         
18         //读取该文件的内容存储到一个字符串中    
19         String line = br.readLine();
20         br.close();
21         
22         //将字符串转换为字符数组
23         char[] chs = line.toCharArray();
24         
25         //对字符数组排序
26         Arrays.sort(chs);
27         
28         //将排序后的字符数组转换为字符串
29         String s = new String(chs);
30         
31         //将转换过来的字符串再次写入b.txt
32          bw.write(s);
33          bw.newLine();
34          bw.close();
35         
36     }
37 
38 }


J:用Reader模拟BufferedReader的特有功能

 1 /*
 2  * 用Reader模拟BufferedReader的readLine()功能
 3  * readLine():一次读取一行,根据换行符判断是否结束,只返回内容不返回换行符
 4  */
 5 public class MyBufferedReader {
 6 
 7     private Reader r;
 8     
 9     public MyBufferedReader(Reader r){
10         this.r = r;
11     }
12     
13     //写一个方法,返回值是一个字符串
14     public String readLine() throws IOException{
15         StringBuffer sb = new StringBuffer();
16         
17         int ch = 0;
18         while((ch = r.read()) != -1){
19             if(ch == '
'){
20                 continue;
21             }
22             if(ch == '
'){
23                 return sb.toString();
24             }else{
25                 sb.append(ch);
26             }
27         }
28         
29         return null;
30         
31     }
32     
33     //关闭方法
34     public void close() throws IOException{
35         this.r.close();
36     }
37 }


K:模拟LineNumberReader的特有功能

 1 /*
 2  * BufferedReader
 3  *     LineNumberReader
 4  *         public int getLineNumber()获取当前行号
 5  *         public void setLineNumber(int lineNumber)
 6  *         设置  显示行号
 7  */
 8 public class LineNumberReaderDemo {
 9     public static void main(String[] args) throws IOException {
10         LineNumberReader lnr = new LineNumberReader(new FileReader("a.txt"));
11         
12         //设置从某一行编号开始
13         lnr.setLineNumber(10);
14         String line = null;
15         while((line = lnr.readLine()) != null){
16             System.out.println(lnr.getLineNumber() + ":" + line);
17         }
18         
19         lnr.close();
20     }
21 
22 }
原文地址:https://www.cnblogs.com/lyywj170403/p/9273010.html