黑马程序员 Java自学总结十四 IO流

来源:互联网 发布:网络直播模式 编辑:程序博客网 时间:2024/04/30 01:53

------ ASP.Net+Android+IO开发.Net培训期待与您交流! ------

总结内容来源于黑马毕老师的java基础教学视频


IO

IO流,用来处理设备间的数据传输,Java中对数据的操作是通过流的方式,用于操作流的对象都在IO包中.

流按流向可分为输入流和输入流

流按操作的数据可分为字节流和字符流

字节流操作的是字节,字符流操作的是字符。

先有字节流,为了方便人们识别和操作,将字节编码通过编码表生成字符,由此在字节流的基础上产生了字符流。

JavaIO流中主要由四个基类:

字符流的基类:WriterReader

字节流的基类:InputStreamOutputStream

字符输出流 Writer

找到一个专门用于操作文件的Writer子类对象FileWriter

               (前缀是该流对象的功能,后缀是父类名)

示例代码
[java] view plaincopy
  1. import java.io.*;  
  2. class  FileWriterDemo  
  3. {  
  4.      public static void main(String[] args) throws IOException  
  5.      {  
  6.           //创建一个FileWriter对象,该类对象一被初始化就必须要明确被操作的文件  
  7.           //而且该文件会被创建到指定目录下,如果该目录下已有同名文件,将被覆盖.  
  8.           //其实该步就是在明确数据要存放的目的地  
  9.           FileWriter fw = new FileWriter("demo.txt");  
  10.   
  11.           //调用write方法,将字符串写到流中  
  12.           fw.write("dwadwadwa");  
  13.   
  14.           //刷新流对象中的缓冲中的数据  
  15.           //刷新到目的地中.  
  16.           //fw.flush();  
  17.   
  18.           //关闭流资源,关闭前会刷新一次内部的缓冲数据  
  19.           //将数据刷到目的地中  
  20.           //和flush 的区别:flush刷新,流可以继续使用,close刷新后,流关闭.  
  21.           fw.close();  
  22.      }  
  23. }  

IO异常的处理方式.

[java] view plaincopy
  1. import java.io.*;  
  2. class FileWriterDemo2  
  3. {  
  4.      public static void main(String[] args)  
  5.      {  
  6.           //建立并初始化流  
  7.           FileWriter fw = null;  
  8.           try  
  9.           {  
  10.                fw = new FileWriter("demo.txt");  
  11.                fw.write("abcdefg");  
  12.           }  
  13.           catch (IOException e)  
  14.           {  
  15.                System.out.println(e.toString());  
  16.           }  
  17.           finally  
  18.           {  
  19.                try  
  20.                {  
  21.                     //防止出现null异常,先判断fw是否为null  
  22.                     if(fw!=null)  
  23.                          fw.close();                               
  24.                }  
  25.                catch (IOException e)  
  26.                {  
  27.                     System.out.println(e.toString());  
  28.                }  
  29.           }  
  30.      }  
  31. }  

演示对已有文件的数据续写.

[java] view plaincopy
  1. import java.io.*;  
  2. class FileWriterDemo3  
  3. {  
  4.      public static void main(String[] args)  
  5.      {  
  6.           FileWriter fw = null;  
  7.           try  
  8.           {  
  9.                //传递一个true参数,代表不覆盖已有文件.并在已有文件的末尾处进行数据的续写  
  10.                fw = new FileWriter("demo.txt",true);  
  11.                //windows中换行是\r\n  
  12.                fw.write("haha\r\nxiexie");  
  13.                 
  14.           }  
  15.           catch (IOException e)  
  16.           {  
  17.                System.out.println(e.toString());  
  18.           }  
  19.           finally  
  20.           {  
  21.                try  
  22.                {  
  23.                     if(fw!=null)  
  24.                     fw.close();                     
  25.                }  
  26.                catch (IOException e)  
  27.                {  
  28.                     System.out.println(e.toString());  
  29.                }  
  30.           }  
  31.      }  
  32. }  

字符输入流 Reader

找到一个专门用于读取的字符输入流FileReader

示例代码

[java] view plaincopy
  1. /* 
  2. 文件的读取 
  3. 第一种方式:通过每次取出一个字符的方式读取 
  4. read()返回的字符的10进制数字. 
  5. */  
  6. import java.io.*;  
  7. class FileReaderDemo  
  8. {  
  9.      public static void main(String[] args)  
  10.      {  
  11.           FileReader fr = null;  
  12.           try  
  13.           {  
  14.                //创建一个文件读取流对象,和指定名称的文件相关联.  
  15.                //要保证该文件是已经存在的,如果不存在,会发生FIleNotFoundException异常  
  16.                fr = new FileReader("demo.txt");  
  17.                int i = 0;  
  18.                while((i=fr.read())!=-1)  
  19.                {  
  20.                     System.out.println("i="+(char)i);  
  21.                }  
  22.           }  
  23.           catch (IOException e)  
  24.           {  
  25.                System.out.println(e.toString());  
  26.           }  
  27.           finally  
  28.           {  
  29.                try  
  30.                {  
  31.                     if(fr!=null)  
  32.                          fr.close();  
  33.                }  
  34.                catch (IOException e)  
  35.                {  
  36.                     System.out.println(e.toString());  
  37.                }  
  38.           }  
  39.      }  
  40. }  
[java] view plaincopy
  1. /* 
  2. 第二种方式:通过字符数组进行读取. 
  3. */  
  4. import java.io.*;  
  5. class FileReaderDemo2  
  6. {  
  7.      public static void main(String[] args)  
  8.      {  
  9.           FileReader fr = null;  
  10.           try  
  11.           {  
  12.                fr = new FileReader("demo.txt");  
  13.                //定义一个字符数组,用于存储读取到的字符  
  14.                //该read(char[])返回的是读到的字符个数  
  15.                char[] ch = new char[1024];  
  16.                int num = 0;  
  17.                while ((num=fr.read(ch))!=-1)  
  18.                {  
  19.                     System.out.println(new String(ch,0,num));  
  20.                }  
  21.                 
  22.                 
  23.           }  
  24.           catch (IOException e)  
  25.           {  
  26.                System.out.println(e.toString());  
  27.           }  
  28.           finally  
  29.           {  
  30.                try  
  31.                {  
  32.                     if(fr!=null)  
  33.                          fr.close();  
  34.                }  
  35.                catch (IOException e)  
  36.                {  
  37.                     System.out.println(e.toString());  
  38.                }  
  39.           }  
  40.      }  
  41. }  

[java] view plaincopy
  1. //文件的读取练习  
  2. import java.io.*;  
  3. class FileReaderTest  
  4. {  
  5.      public static void main(String[] args)  
  6.      {  
  7.           FileReader fr = null;  
  8.           try  
  9.           {  
  10.                fr = new FileReader("DateDemo.java");  
  11.                char[] ch = new char[1024];  
  12.                int num = 0;  
  13.                while ((num=fr.read(ch))!=-1)  
  14.                {  
  15.                     System.out.println(String.valueOf(ch));  
  16.                }                
  17.           }  
  18.           catch (IOException e)  
  19.           {  
  20.                System.out.println(e.toString());  
  21.           }  
  22.           finally  
  23.           {  
  24.                try  
  25.                {  
  26.                     if(fr!=null)  
  27.                          fr.close();  
  28.                }  
  29.                catch (IOException e)  
  30.                {  
  31.                     System.out.println(e.toString());  
  32.                }  
  33.           }  
  34.      }  
  35. }  

字符流(拷贝文本文件练习)用到FileWriter和FileReader

[java] view plaincopy
  1. /* 
  2. 将C盘一个文本文件复制到D盘 
  3.  
  4. 复制原理: 
  5. 其实就是讲C盘下的文件数据存储到D盘的一个文件中 
  6.  
  7. 步骤: 
  8. 1.在D盘创建一个文件,用于存储C盘文件中的数据. 
  9. 2.定义读取流和C盘文件关联. 
  10. 3.通过不断的读写完成数据存储. 
  11. 4.关闭资源. 
  12. */  
  13. import java.io.*;  
  14. class CopyTest  
  15. {  
  16.      public static void main(String[] args) throws IOException  
  17.      {  
  18.           copy_1();  
  19.      }  
  20.      public static void copy_1()throws IOException  
  21.      {           
  22.           FileWriter fw = null;  
  23.           FileReader fr = null;  
  24.           try  
  25.           {  
  26.                fw = new FileWriter("d:\\demo.txt");  
  27.                char[] copy = new char[1024];  
  28.                fr = new FileReader("c:\\demo.txt");  
  29.                int len = 0;  
  30.                while ((len=fr.read(copy))!=-1)  
  31.                {  
  32.                     fw.write(copy,0,len);  
  33.                }                
  34.           }  
  35.           catch (IOException e)  
  36.           {  
  37.                throw new RuntimeException("读写失败");  
  38.           }  
  39.           finally  
  40.           {  
  41.                if(fr!=null)  
  42.                     try  
  43.                     {  
  44.                          fr.close();                                         
  45.                     }  
  46.                     catch (IOException e)  
  47.                     {  
  48.                          System.out.println(e.toString());  
  49.                     }  
  50.                if(fw!=null)                          
  51.                     try  
  52.                     {  
  53.                          fw.close();                                         
  54.                     }  
  55.                     catch (IOException e)  
  56.                     {  
  57.                          System.out.println(e.toString());  
  58.                     }  
  59.           }  
  60.      }      
  61. }  

BufferdWriter和BufferedReader字符流缓冲区

字符流缓冲区的出现是为了提高流的操作效率而出现的.

所以在创建缓冲区之前,必须要先有流对象

该缓冲区中提供了一个跨平台的换行符

newLine():

            原理:底层调用read()方法,把数据存到临时数组中,

                  读到回车符的时候,就把数组中的数据全部返回.


[java] view plaincopy
  1. import java.io.*;  
  2. class  BufferedWriterDemo  
  3. {  
  4.      public static void main(String[] args) throws IOException  
  5.      {  
  6.           //创建一个字符写入流对象  
  7.           FileWriter fw = new FileWriter("buf.txt");  
  8.   
  9.           //为了提高字符写入流效率,加入缓冲技术.  
  10.           //只要将需要被提高效率的流对象作为参数传递给缓冲区的构造函数即可  
  11.           BufferedWriter bw = new BufferedWriter(fw);  
  12.   
  13.           for (int x=0; x<5; x++)  
  14.           {  
  15.                bw.write("abcde");  
  16.                //记住,只要用到缓冲区,就要记得刷新  
  17.                bw.newLine();  
  18.                bw.flush();  
  19.           }  
  20.   
  21.           //其实关闭缓冲区,就是再关闭缓冲区流对象.  
  22.           bw.close();  
  23.   
  24.      }  
  25. }  

该缓冲区提供了一个一次读取一行的方法readLine(),返回一个字符串,方便于对文本数据的获取.

当返回null,表示读到文件末尾.

[java] view plaincopy
  1. import java.io.*;  
  2. class BufferedReaderDemo  
  3. {  
  4.      public static void main(String[] args) throws IOException  
  5.      {  
  6.           //创建一个读取流对象和文件相关联  
  7.           FileReader fr = new FileReader("buf.txt");  
  8.   
  9.           //为了提高效率,加入缓冲技术.将字符读取流对象作为参数传递给缓冲对象.  
  10.           BufferedReader br = new BufferedReader(fr);  
  11.   
  12.           String line = null;  
  13.           while ((line = br.readLine())!=null)  
  14.           {  
  15.                 System.out.println("line="+line);  
  16.           }  
  17.      }  
  18. }  

字符流(通过缓冲区复制.java文件)


[java] view plaincopy
  1. /* 
  2. 通过缓冲区复制一个.java文件. 
  3. */  
  4. import java.io.*;  
  5. class CopyTextByBuf  
  6. {  
  7.      public static void main(String[] args)  
  8.      {  
  9.           FileWriter fw = null;  
  10.           FileReader fr = null;  
  11.           BufferedWriter bw = null;  
  12.           BufferedReader br = null;  
  13.           try  
  14.           {  
  15.                fw = new FileWriter("CopyByBuf.txt");  
  16.                fr = new FileReader("BufferedWriterDemo.java");  
  17.                bw = new BufferedWriter(fw);  
  18.                br = new BufferedReader(fr);      
  19.                String line = null;  
  20.                while ((line = br.readLine())!=null)  
  21.                {  
  22.                     bw.write(line);  
  23.                     bw.newLine();  
  24.                     bw.flush();  
  25.                }  
  26.           }  
  27.           catch (IOException e)  
  28.           {  
  29.                throw new RuntimeException("读写失败");  
  30.           }  
  31.           finally  
  32.           {  
  33.                if(bw!=null)  
  34.                try  
  35.                {  
  36.                     bw.close();                     
  37.                }  
  38.                catch (IOException e)  
  39.                {  
  40.                     throw new RuntimeException("无此对象");  
  41.                }  
  42.                if(br!=null)  
  43.                try  
  44.                {  
  45.                     br.close();                     
  46.                }  
  47.                catch (IOException e)  
  48.                {  
  49.                     throw new RuntimeException("无此对象");  
  50.                }  
  51.           }  
  52.      }  
  53. }  

字符流(readLine方法的原理和写法)

[java] view plaincopy
  1. /* 
  2. 明白了BufferedReader类中特有方法readLine的原理后 
  3. 可以自定义一个类中包含一个功能和readLine一致的方法 
  4. 来模拟一下BufferedReader 
  5. */  
  6. import java.io.*;  
  7. class  MyBufferedDemo1  
  8. {  
  9.      public static void main(String[] args)  
  10.      {  
  11.           FileReader fr = null;  
  12.           MyBufferedReader mbr =null;      
  13.           try  
  14.           {  
  15.                fr = new FileReader("CopyByBuf.txt");  
  16.                mbr = new MyBufferedReader(fr);  
  17.                String s = null;  
  18.                while ((s = mbr.myReadLine())!=null)  
  19.                {  
  20.                     System.out.println(s);  
  21.                }                
  22.           }  
  23.           catch (IOException e)  
  24.           {  
  25.                throw new RuntimeException(e);  
  26.           }  
  27.           finally  
  28.           {  
  29.                if(mbr!=null)  
  30.                try  
  31.                {  
  32.                     mbr.myClose();                                                             
  33.                }  
  34.                catch (IOException e)  
  35.                {  
  36.                     throw new RuntimeException(e);  
  37.                }  
  38.           }  
  39.      }  
  40. }  
  41. class MyBufferedReader  
  42. {  
  43.      private FileReader r;  
  44.      MyBufferedReader(FileReader r)  
  45.      {  
  46.           this.r = r;  
  47.      }  
  48.      public String myReadLine() throws IOException  
  49.      {  
  50.                //定义一个临时容器.原BufferedReader封装的字符数组.  
  51.                //为了演示方便.定义一个StringBuilder容器.因为最终还是要将数组变成字符串.  
  52.                StringBuilder sb = new StringBuilder();  
  53.                int ch = 0;  
  54.                while ((ch = r.read())!=-1)  
  55.                {  
  56.                     if(ch=='\r')  
  57.                          continue;  
  58.                     if(ch=='\n')  
  59.                          return sb.toString();  
  60.                     sb.append((char)ch);  
  61.                }  
  62.                //上面的循环语句,只能返回有换行符的每行  
  63.                //这个判断语句在最后一行没有换行符的时候,仍然能返回最后一行  
  64.                if(sb.length()!=0)  
  65.                     return sb.toString();  
  66.                return null;                
  67.      }  
  68.      public void myClose() throws IOException  
  69.      {  
  70.           r.close();  
  71.      }  
  72. }  

装饰设计模式

[java] view plaincopy
  1. /* 
  2. 装饰设计模式: 
  3. 当想要对已有的对象进行功能增强时, 
  4. 可以定义一个类,将已有对象传入,基于已有对象的功能, 
  5. 并提供此功能加强功能,那么自定义的类称为装饰类. 
  6.  
  7. 装饰类通常会通过构造方法接收被装饰的对象. 
  8. 并基于被装饰的对象的功能,提供更强的功能. 
  9. */  
  10. class Person  
  11. {  
  12.      public void chifan()  
  13.      {  
  14.           System.out.println("吃饭");  
  15.      }  
  16. }  
  17. //SuperPerson就是Person的装饰类,它增强了Person的吃饭方法  
  18. class SuperPerson  
  19. {  
  20.      private Person p;  
  21.      SuperPerson(Person p)  
  22.      {  
  23.           this.p = p;  
  24.      }  
  25.      public void superChifan()  
  26.      {  
  27.           System.out.println("开胃酒");  
  28.           p.chifan();  
  29.           System.out.println("甜点");  
  30.           System.out.println("来一根");  
  31.      }  
  32. }  
  33.   
  34. class  PersonDemo  
  35. {  
  36.      public static void main(String[] args)  
  37.      {  
  38.           Person p = new Person();  
  39.           SuperPerson sp = new SuperPerson(p);  
  40.           sp.superChifan();  
  41.      }  
  42. }  

继承和装饰的区别和特点

继承和装饰的区别和特点

MyReader//专门用于读取数据的类

     |--MyTextReader

          |--MyBufferedTextReader

     |--MyMediaReader

          |--MyBufferedMediaReader

     |--MyDataReader

          |--MyBufferedDataReader

class MyBufferedReader

{

     MyBufferedReader(MyBufferedTextReader text)

     {}

     MyBufferedReader(MyBufferedMediaReader media)

     {}

     MyBufferedReader(MyDataReader data)

     {}

}

上面的类扩展性很差,找到其参数的共同类型.通过多态的形式,可以提高其扩展性

class MyBufferedRead extends MyReader

{

     MyBufferedRreader(MyReader r)

     {}

}

MyReader//专门用于读取数据的类

     |--MyTextReader

     |--MyMediaReader

     |--MyDataReader

     |--MyBufferedReader

装饰模式比继承要灵活,避免了继承体系臃肿.

而且降级了类于类之间的关系.

装饰类因为增强已有对象,具备的功能和已有的是相同,只不过提供了更强功能.

所以装饰类和被装饰类通常都是一个体系中的.


自定义一个Reader的装饰类

[java] view plaincopy
  1. /* 
  2. 自定义一个继承Reader的装饰类,并复写了Reader的抽象方法. 
  3. */  
  4. import java.io.*;  
  5. class MyBufferedReader extends Reader  
  6. {  
  7.      private Reader r;  
  8.      MyBufferedReader(Reader r)  
  9.      {  
  10.           this.r = r;  
  11.      }  
  12.      //增强了Reader的read()方法  
  13.      public String readLine() throws IOException  
  14.      {  
  15.                //定义一个临时容器.原BufferedReader封装的字符数组.  
  16.                //为了演示方便.定义一个StringBuilder容器.因为最终还是要将数组变成字符串.  
  17.                StringBuilder sb = new StringBuilder();  
  18.                int ch = 0;  
  19.                while ((ch = r.read())!=-1)  
  20.                {  
  21.                     if(ch=='\r')  
  22.                          continue;  
  23.                     if(ch=='\n')  
  24.                          return sb.toString();  
  25.                     sb.append((char)ch);  
  26.                }  
  27.                //上面的循环语句,只能返回有换行符的每行  
  28.                //这个判断语句在最后一行没有换行符的时候,仍然能返回最后一行  
  29.                if(sb.length()!=0)  
  30.                     return sb.toString();  
  31.                return null;                
  32.      }  
  33.      //复写了Reader的read(char[],int,int)方法  
  34.      public int read(char[] ch,int a,int b) throws IOException  
  35.      {  
  36.           return r.read(ch,a,b);  
  37.      }  
  38.      //复写了Reader的close()方法  
  39.      public void close() throws IOException  
  40.      {  
  41.           r.close();  
  42.      }  
  43. }  

LineNumberReader也是一个包装类,它在BufferedReader的基础上增加了一个记录行号的功能,而记录行号是在readLine方法中操作的,所以它继承了BufferedReader并复写了readLine方法,同时增加了getLineNumbersetLineNumber方法。

LineNumberReader读取行号的原理

[java] view plaincopy
  1. /* 
  2. 解析LineNumberReader的原理,通过自定义一个功能相同的类来体现. 
  3. */  
  4. import java.io.*;  
  5. class MyLineNumberBuffered extends BufferedReader  
  6. {  
  7.      private Reader r;  
  8.      private int count;  
  9.      //调用父类构造函数,提高代码复用  
  10.      MyLineNumberBuffered(Reader r)  
  11.      {  
  12.           super(r);  
  13.      }  
  14.      //调用父类readLine方法,提高代码复用性  
  15.      public String readLine() throws IOException  
  16.      {  
  17.           //每次调用readLine时count就自增一次  
  18.           count++;  
  19.           return super.readLine();  
  20.      }  
  21.      public int getLineNumber()  
  22.      {  
  23.           return count;  
  24.      }  
  25.      public int setLineNumber(int count)  
  26.      {  
  27.           return this.count = count;  
  28.      }  
  29. }  
  30. class  MyLineNumberBufferedDemo  
  31. {  
  32.      public static void main(String[] args) throws IOException  
  33.      {  
  34.           FileReader fr = new FileReader("CopyByBuf.txt");  
  35.           MyLineNumberBuffered mlnb = new MyLineNumberBuffered(fr);  
  36.           String s = null;  
  37.           mlnb.setLineNumber(100);  
  38.           while ((s = mlnb.readLine())!=null)  
  39.           {  
  40.                System.out.println(mlnb.getLineNumber()+"::"+s);  
  41.           }  
  42.      }  
  43. }  

字节流

字节流的两个基类是InputStreamOutputStream,相应的缓冲区是BufferedInputStreamBufferedOutputStream

它的操作与字符流类似,可以参与字符流的定义、读取、写入、处理异常的格式。

只不过是处理的数据不同,因为对于非字符的数据,比如图片、视频、音频文件(例如mp3)等,这些文件只能用字节流对之进行操作。

字节流的写操作,不用刷新动作,也能写入目的地,这是为什么?

字符流底层用也的字节流,因为涉及编码,比如写一个汉字,它有两个字节,你不能读一个字节就写入,而要等到两个字节都读取完后,才写入,

所以必须要有flush机制。而字节流,不涉及编码,可以读一个就写一个而不出现问题,所以不用刷新也能写入。

字节流特有的读取方式:available()方法可以知道文件的所有字节数,以此可以定义一个刚

刚好的字节数组,只用读取一次,然后写入来完成文件复制。但注意:如果字节数过大,会造成内存溢出。

字节流读写示例:

[java] view plaincopy
  1. /* 
  2. 字节流 
  3. 读 InputStream     写 OutputStream 
  4.  
  5. 需求:想要操作图片数据.这时就要用到字节流. 
  6. */  
  7. import java.io.*;  
  8. class  FileStream  
  9. {  
  10.      public static void main(String[] args) throws IOException  
  11.      {  
  12.           writeFile();  
  13.           readFile_1();  
  14.           System.out.println();  
  15.           readFile_2();  
  16.           System.out.println();  
  17.           readFile_3();      
  18.      }  
  19.   
  20.      public static void writeFile() throws IOException  
  21.      {  
  22.           FileOutputStream fos = new FileOutputStream("fos.txt");           
  23.           fos.write("abcde".getBytes());  
  24.           fos.close();  
  25.      }  
  26.      public static void readFile_1() throws IOException  
  27.      {  
  28.           FileInputStream fis = new FileInputStream("fos.txt");  
  29.           int by = 0;  
  30.           while ((by=fis.read())!=-1)  
  31.           {  
  32.                System.out.print((char)by);  
  33.           }  
  34.           fis.close();  
  35.      }  
  36.      public static void readFile_2() throws IOException  
  37.      {  
  38.           FileInputStream fis = new FileInputStream("fos.txt");  
  39.           byte[] bys = new byte[1024];  
  40.           int by = 0;  
  41.           while ((by=fis.read(bys))!=-1)  
  42.           {  
  43.                System.out.print(new String(bys,0,by));  
  44.           }  
  45.           fis.close();  
  46.      }  
  47.      public static void readFile_3() throws IOException  
  48.      {  
  49.           FileInputStream fis = new FileInputStream("fos.txt");  
  50.           byte[] bys = new byte[fis.available()];//定义一个刚刚好的数组,  
  51.           fis.read(bys);                                   //不建议用这种.  
  52.           System.out.println(new String(bys));  
  53.           fis.close();  
  54.      }  
  55. }  

复制一个图片

[java] view plaincopy
  1. /* 
  2. 复制一个图片 
  3. 思路: 
  4. 1.用字节读取流对象和图片关联. 
  5. 2.用字节写入流创建一个图片文件.用于存储获取到的图片数据. 
  6. 3.通过循环读写,完成数据的存储. 
  7. 4.关闭资源 
  8. */  
  9. import java.io.*;  
  10. class CopyPic  
  11. {  
  12.      public static void main(String[] args)  
  13.      {  
  14.           FileInputStream fis = null;  
  15.           FileOutputStream fos = null;  
  16.           try  
  17.           {  
  18.                fis = new FileInputStream("c:\\1.jpg");  
  19.                fos = new FileOutputStream("c:\\2.jpg");  
  20.                byte[] bys = new byte[1024];  
  21.                int num = 0;  
  22.                while ((num = fis.read(bys))!=-1)  
  23.                {  
  24.                     fos.write(bys);  
  25.                }                
  26.           }  
  27.           catch (IOException e)  
  28.           {  
  29.                System.out.println("复制图片失败");  
  30.           }  
  31.           finally  
  32.           {  
  33.                try  
  34.                {  
  35.                     if(fis!=null)  
  36.                          fis.close();  
  37.                }  
  38.                catch (IOException e)  
  39.                {  
  40.                     System.out.println("读取关闭失败");  
  41.                }  
  42.                try  
  43.                {  
  44.                     if(fos!=null)  
  45.                          fos.close();  
  46.                }  
  47.                catch (IOException e)  
  48.                {  
  49.                     System.out.println("写入关闭失败");  
  50.                }  
  51.           }  
  52.      }  
  53. }  

利用字节流缓冲区复制MP3

[java] view plaincopy
  1. import java.io.*;  
  2. class  CopyMp3  
  3. {  
  4.      public static void main(String[] args)  
  5.      {  
  6.           FileInputStream fis = null;  
  7.           FileOutputStream fos = null;  
  8.           BufferedInputStream bis = null;  
  9.           BufferedOutputStream bos = null;  
  10.           try  
  11.           {  
  12.                fis = new FileInputStream("c:\\1.mp3");  
  13.                fos = new FileOutputStream("c:\\2.MP3");  
  14.                bis = new BufferedInputStream(fis);  
  15.                bos = new BufferedOutputStream(fos);  
  16.                int num =0;  
  17.                while ((num=bis.read())!=-1)  
  18.                {  
  19.                     bos.write(num);  
  20.                }  
  21.           }  
  22.           catch (IOException e)  
  23.           {  
  24.                System.out.println("复制MP3失败");  
  25.           }  
  26.           finally  
  27.           {  
  28.                try  
  29.                {  
  30.                     if(bis!=null)  
  31.                          bis.close();  
  32.                }  
  33.                catch (IOException e)  
  34.                {  
  35.                     System.out.println("读取关闭失败");  
  36.                }  
  37.                try  
  38.                {  
  39.                     if(bos!=null)  
  40.                          bos.close();  
  41.                }  
  42.                catch (IOException e)  
  43.                {  
  44.                     System.out.println("写入关闭失败");  
  45.                }  
  46.           }  
  47.      }  
  48. }  

自定义字节流缓冲区

[java] view plaincopy
  1. import java.io.*;  
  2. class MyBufferedInputStream  
  3. {  
  4.      //定义计数器count,角标pos  
  5.      private int count = 0,pos = 0;  
  6.      byte[] bys = new byte[1024*1024];  
  7.      private InputStream in;  
  8.      MyBufferedInputStream(InputStream in)  
  9.      {  
  10.           this.in = in;  
  11.      }  
  12.      public int myRead() throws IOException  
  13.      {  
  14.           //计数器是否为0  
  15.           if(count==0)  
  16.           {  
  17.                count = in.read(bys);//把字节流读取的数据存到数组中  
  18.                if(count<0)//字节流读取到数据的结尾处就返回-1  
  19.                     return -1;  
  20.                pos = 0;//初始化角标pos为0  
  21.                byte b = bys[pos];  
  22.                count--;//计数器count自减一次  
  23.                pos++;//角标pos自增  
  24.                return b&255;  
  25.           }  
  26.           else if(count>0)  
  27.           {  
  28.                int b = bys[pos];  
  29.                count--;  
  30.                pos++;  
  31.                return b&255;//byte型的b的二进制有可能是1111-1111,十进制就是-1,  
  32.           }                    //就会直接中止read,所以要&255取后8位并把前面补上0  
  33.           else  
  34.                return -1;           
  35.      }  
  36.      public void myClose() throws IOException  
  37.      {  
  38.           in.close();  
  39.      }  
  40.   
  41. }  
  42. class  MyBufferedInputStreamDemo  
  43. {  
  44.      public static void main(String[] args) throws IOException  
  45.      {  
  46.           long start = System.currentTimeMillis();  
  47.           FileOutputStream ou = new FileOutputStream("c:\\3.mp3");  
  48.           FileInputStream in = new FileInputStream("c:\\1.mp3");  
  49.           MyBufferedInputStream mbis = new MyBufferedInputStream(in);  
  50.           int num = 0;  
  51.           while ((num = mbis.myRead())!=-1)  
  52.           {  
  53.                ou.write(num);                
  54.           }  
  55.           mbis.myClose();  
  56.          long end = System.currentTimeMillis();  
  57.           System.out.println((end-start)+"毫秒");  
  58.      }  
  59. }  

读取键盘录入。  

System.out:对应的是标准输出设备,控制台。  

System.in:对应的是标准的输入设备,键盘。 

通过键盘录入数据。  

当录入一行数据后,就将改行数据打印。  

如果录入的数据是over,那么停止录入。

[java] view plaincopy
  1. /* 
  2. 读取键盘录入. 
  3. System.out:对应标准输出设备,控制台 
  4. System.in:对应标准输入设别:键盘. 
  5. */  
  6. import java.io.*;  
  7. class ReadIn  
  8. {  
  9.      public static void main(String[] args) throws IOException  
  10.      {  
  11.           InputStream in = System.in;  
  12.           StringBuilder sb = new StringBuilder();  
  13.   
  14.           while (true)  
  15.           {                
  16.                int ch = in.read();      
  17.                if(ch=='\r')  
  18.                     continue;  
  19.                if(ch=='\n')//如果是回车符  
  20.                {  
  21.                     String s = sb.toString();//就把sb转成字符串  
  22.                     if("over".equals(s))//判断是否是over  
  23.                          break;//如果是,就停止循环  
  24.                     System.out.println(s.toUpperCase());//如果不是,就输出大写  
  25.                     sb.delete(0,sb.length());//输出后,把sb清空,下次继续存入  
  26.                }  
  27.                else  
  28.                     sb.append((char)ch);                                           
  29.           }  
  30.      }  
  31. }  

通过刚才的键盘录入一行数据并打印其大写,发现其实就是读一行数据的原理.

也就是readLine方法

能不能直接使用readLine方法来完成键盘录入的一行数据的读取呢?

readLine方法是字符流BufferedReader类中的方法.

而键盘录入的read方法是字节流InputStream的方法.

那么能不能将字节流转成字符流在使用字符缓冲区的readLine方法呢?

API中找到Reader的子类

                         |--InputStreamReader:读取转换流

                         |--OutputStreamWriter:写入转换流

[java] view plaincopy
  1. import java.io.*;  
  2. class  TransStreamDemo  
  3. {  
  4.      public static void main(String[] args) throws IOException  
  5.      {  
  6.           //获取键盘录入对象  
  7. //          InputStream in = System.in;  
  8.           //将字节流对象转成字符流对象,使用转换流InputStreamReader  
  9. //          InputStreamReader isr = new InputStreamReader(in);  
  10.           //为了提高效率,将字符串进行缓冲区技术高效操作.使用BufferedReader  
  11. //          BufferedReader br = new BufferedReader(isr);  
  12.           //最常用的写法,背下来  
  13.           BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
  14.   
  15. //          OutputStream out = System.out;  
  16. //          OutputStreamWriter osw = new OutputStreamWriter(out);  
  17. //          BufferedWriter bw = new BufferedWriter(osw);  
  18.           BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));  
  19.   
  20.           String s = null;  
  21.           while ((s = br.readLine())!=null)  
  22.           {  
  23.                if(s.equals("over"))  
  24.                     break;  
  25.                bw.write(s.toUpperCase());  
  26.                bw.newLine();  
  27.                bw.flush();  
  28.           }  
  29.      }  
  30. }  

流操作的规律

流操作的基本规律:

最痛苦的就是流对象有很多,不知道该用那一个.

通过3个明确来完成.

1.明确源和目的.

     源:输入流.InputStream Reader

     目的:输出流.OutputStream Writer

2.操作的数据是否是纯文本.

     是:字符流

     不是:字节流

3.当体系明确后,明确要使用哪个具体的对象.

     通过设备来进行区分:

     源设备有:内存,硬盘,键盘

     目的设别:内存,硬盘,控制台

------------------------------------------------------------------------------

范例 1.将一个文本文件中数据存储到另一个文件中.复制文件

   源:因为是源,所以使用读取流.InputStream Reader

       是不是操作文本文件?

       是!这时就可以选择Reader

       这样体系就明确了

       接下来要明确要使用该体系中的那个对象.

       明确设别:硬盘上的文件

       Reader体系中可以操作文件的对象是FileReader

       是否需要提高效率加入Reader体系中的缓冲区BufferedReader.

       FileReader fr = new FileReader("一个文件");

       BufferedReader br = new BufferedReader(fr);

目的:OutputStream Writer

       是不是纯文本?

       是!Writer

       设别:硬盘,一个文件

       Writer体系中可以操作文件的对象FileWriter

       是否需要提高效率加入Writer体系中的缓冲区BufferedWriter.

       FileWriter fw = new FileWriter("另一个文件");

       BufferedWriter bw = new BufferedWriter(fw);

------------------------------------------------------------------------------

练习:将一个图片文件中数据存储到另一个文件中,复制文件,按照上面格式完成三个明确.

   源:InputStream Reader

       是不是操作文本文件?

       不是!选择InputStream

       设备:硬盘上的文件

       InputStream体系中可以操作文件的是FileInputStream

       是否需要提高效率加入InputStream体系中的BufferedInputStream.

       FileInputStream fis = new FileInputStream("一个图片");

       BufferedInputStream bis = new BufferedInputStream(fis);

目的:是不是纯文本?

      不是!OutputStream

       设备:硬盘,图片

       OutputStream体系中可以操作文件的是FileOutputStream

       是否需要提高效率加入OutputStream体系中的BufferedOutputStream.

       FileOutputStream fos = new FileOutputStream("另一个图片");

       BufferedOutputStream bos = new BufferedOutputStream(fos);

-------------------------------------------------------------------------------

范例 2.将键盘录入的数据保存到一个文件中.

   源:是不是纯文本?

      是! Reader

       设备:键盘,对应的对象是System.in

       不是选择Reader? System.in对应的不是字节流InputStream?

       为了操作键盘的文本数据方便,转成字符流按照字符串操作是最方便的.

       所以既然明确了Reader,那么就将System.in转成Reader.

       用Reader体系中的读取转换流,InputStreamReader

       是否需要提高效率用到Reader体系中的BufferedReader.

       InputStream in = System.in;

       InputStreamReader isr = new InputStreamReader(in);

       BufferedReader br = new BufferedReader(isr);

目的:是不是纯文本?

      是! Writer

       设备:硬盘,txt文件.使用FileWriter

      

       是否需要提高效率用到Writer体系中的BufferedWriter

       FileWriter fw = new FileWriter("xxx.txt");

       BufferedWriter bw = new BufferedWriter(fw);

****************************************************************************

扩展:

       扩展一下.想要把录入的数据按照指定的编码表(utf-8),将数据存储到文件中.

目的:是不是纯文本?

      是! Writer

       设备:硬盘,txt文件.使用FileWriter

       但是FileWriter是使用默认的编码表

      

       但是存储时,需要加入指定的编码表,而指定的表码表只有转换流可以指定

       所以要使用的对象是写入转换流OutputStreamWriter

       而该转换流对象要接受一个可以操作文件的字节输出流,FileOutputStream

      

       FileOutputStream fos = new FileOutputStream("d.txt");

       OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");

       需要高效嘛需要!

       BufferedWriter bw = new BufferedWriter(osw);

       所以,记住转换流什么时候使用.字符和字节之间的桥梁,

       通常涉及到字符编码转换时,需要用到转换流.    

[java] view plaincopy
  1. import java.io.*;  
  2. class  TransStreamDemo2  
  3. {  
  4.      public static void main(String[] args) throws IOException  
  5.      {  
  6.           BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
  7.            
  8.           FileOutputStream fos = new FileOutputStream("d.txt");  
  9.           OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");  
  10.           BufferedWriter bw = new BufferedWriter(osw);  
  11.   
  12.           String s = null;  
  13.           while ((s = br.readLine())!=null)  
  14.           {  
  15.                if(s.equals("over"))  
  16.                     break;  
  17.                bw.write(s.toUpperCase());  
  18.                bw.newLine();  
  19.                bw.flush();  
  20.           }  
  21.      }  
  22. }  
流操作的练习

[java] view plaincopy
  1. /* 
  2. 练习:将一个文本数据打印在控制台上,按照三个明确来完成 
  3.  
  4.    源:InputStream Reader 
  5.       是否为纯文本? 是! Reader 
  6.        设备:硬盘,文本文件.使用FileReader 
  7.  
  8.        需要提高效率嘛? 需要! 
  9.        Reader体系中的BufferedReader 
  10.  
  11.        FileReader fr = new FileReader("d.xxt"); 
  12.        BufferedReader br = new BufferedReader(fr); 
  13.  
  14. 目的:OutputStream Writer 
  15.       是否为纯文本? 是! Writer 
  16.        设备:控制台,对应的对象是System.out, 
  17.        用到Writer体系中的写入转换流OutputStreamWriter 
  18.  
  19.        需要高效嘛? 需要! 
  20.        Writer体系中的BufferedWriter 
  21.  
  22.        OutputStreamWriter osw = new OutputStreamWriter(System.in); 
  23.        BufferWriter bw = new BufferedWriter(osw); 
  24. */  
  25. import java.io.*;  
  26. class TransStreamTest  
  27. {  
  28.      public static void main(String[] args) throws IOException  
  29.      {  
  30.           System.setOut(new PrintStream("dd.txt"));//重新设置目的out,也可以重新设置源,写法相同  
  31.           FileReader fr = new FileReader("d.txt");  
  32.           BufferedReader br = new BufferedReader(fr);  
  33.   
  34.           OutputStreamWriter osw = new OutputStreamWriter(System.out);  
  35.           BufferedWriter bw = new BufferedWriter(osw);  
  36.            
  37.           String s = null;  
  38.           while ((s=br.readLine())!=null)  
  39.           {  
  40.                bw.write(s);  
  41.                bw.newLine();  
  42.                bw.flush();           
  43.           }  
  44.   
  45.      }  
  46. }  
System类中有可以改变输入输出的方法

前提是必须有调用System.inSystem.out

System.setInInputStream in;改变标准输入

System.setOutPrintStream ps;改变标准输出

异常信息序列化

[java] view plaincopy
  1. import java.io.*;  
  2. import java.util.*;  
  3. import java.text.*;  
  4. class ExceptionInfo  
  5. {  
  6.      public static void main(String[] args)  
  7.      {  
  8.           try  
  9.           {  
  10.                int[] arr = new int[2];  
  11.                System.out.println(arr[3]);  
  12.           }  
  13.           catch (Exception e)  
  14.           {  
  15.                try  
  16.                {  
  17.                     Date d = new Date();  
  18.                     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  19.                     String s = sdf.format(d);  
  20.                     PrintStream ps = new PrintStream("exception.log");  
  21.                     ps.println(s);  
  22.                     System.setOut(ps);                     
  23.                }  
  24.                catch (IOException ie)  
  25.                {  
  26.                     throw new RuntimeException("创建日志文件失败");  
  27.                }  
  28.                e.printStackTrace(System.out);  
  29.           }  
  30.      }  
  31. }  

工具log4j,有很多对象可以方便创建日志信息的建立.


File

文件是一类事物,它有自己的名字、属性、大小、位置、后缀名等属性信息,那么根据面向对象的思想,就可以把它封装描述为一个类,

这个类就java.io包中的File类。File类是文件和目录路径名的抽象表示形式,它可以方便的对文件与文件夹的属性信息进行操作,也可以作为参数传递给流对象。

它弥补了了流的不足,比如流只能操作数据,而不能操作文件的属性与文件夹。

File类常见方法:

1.创建

   boolean createNewFile();在指定位置创建文件,如该文件已存在,不创建,返回false.

                           和输出流不同,不管文件是否存在,都创建,如过有,就覆盖.

   boolean mkdir();创建一级目录

   boolean mkdirs();创建多级目录

2.删除

   boolean delete();删除失败返回false

   void deleteOnExit();在程序退出时删除指定文件.

3.判断

   boolean canExecute();

   boolean canRead();

   boolean canWrite();

   boolean exists();判断文件是否存在.

   boolean isFile();判断是够是文件

   boolean isDirectory();判断是否是目录

   boolean isHidden();是否是隐藏文件

   boolean isAbssolute():是否是绝对路径

4.获取信息

   String getName();

   String getPath();获取封装的路径,封装的什么就获取什么

   String getParent();获取绝对路径中的父目录,如果获取的是相对路径,返回null

                      |--如果相对路径有上一层目录,那么该目录就是返回结果.

   String getAbsolutePath();获取绝对路径

   long lastModifiel();获取最后一次修改时间

   long length();获取文件大小

[java] view plaincopy
  1. class  FileDemo  
  2. {  
  3.      public static void main(String[] args) throws IOException  
  4.      {  
  5.           method_4();  
  6.      }  
  7.      public static void method_4() throws IOException  
  8.      {  
  9.           File f1 = new File("c:\\Test.java");  
  10.           File f2 = new File("c:\\haha.java");  
  11.   
  12.           System.out.println("rename:"+f1.renameTo(f2));//类似剪切,并修改文件名  
  13.      }  
  14.      public static void method_3() throws IOException  
  15.      {  
  16.           File f = new File("FileDemo.java");  
  17.   
  18.           System.out.println("path:"+f.length());  
  19.           System.out.println("path:"+f.getAbsolutePath());  
  20.   
  21.      }  
  22.      public static void method_2() throws IOException  
  23.      {  
  24.           File f = new File("file.txt");  
  25.           f.mkdir();  
  26.           //在判断文件对象是否是文件或者目录时,必须先判断该文件是否存在.  
  27.           //通过exists()判断.  
  28.           System.out.println("dir:"+f.isDirectory());  
  29.           System.out.println("dir:"+f.isFile());  
  30.      }  
  31.      public static void method_1() throws IOException  
  32.      {  
  33.           File f = new File("file.txt");  
  34.           System.out.println("create:"+f.createNewFile());//创建  
  35.           System.out.println("delete:"+f.delete());//删除  
  36.           System.out.println("execute:"+f.canExecute());//判断是否能执行  
  37.           System.out.println("exist:"+f.exists());//判断文件是否存在  
  38.      }  
  39.   
  40.      //创建File对象  
  41.      public static void consMethod()  
  42.      {  
  43.           //将a.txt封装成file对象.可以将已有的和未出现的文件或者文件夹封装成对象.  
  44.           File f1 = new File("c:\\abc\\a.txt");  
  45.            
  46.           //File.separator跨平台的分隔符类似newLine()  
  47.           File f2 = new File("c:"+File.separator+"abc","b.txt");  
  48.            
  49.           File d = new File("c:\\abc");  
  50.           File f3 = new File(d,"c.txt");  
  51.   
  52.           System.out.println("f1:"+f1);  
  53.           System.out.println("f2:"+f2);  
  54.           System.out.println("f3:"+f3);  
  55.      }  
  56. }  

File类中的高级方法    

     File[] listRoots();返回有效的盘符的对象

     String[] list();返回当前目录下所有文件的名称

     String[] list(filter);传递一个过滤器,按照过滤器返回文件名

     File[] listFiles();返回当目录下所有文件的对象


[java] view plaincopy
  1. class FileDemo2  
  2. {  
  3.      public static void main(String[] args)  
  4.      {  
  5.           listFileDemo();  
  6.      }  
  7.      public static void listFileDemo()  
  8.      {  
  9.           File dir = new File("d:\\learn\\day19");  
  10.           //获取当前目录下所有文件的对象.  
  11.           File[] files = dir.listFiles();  
  12.           for (File f : files )  
  13.           {  
  14.                System.out.println(f.getName()+"::"+f.length());  
  15.           }  
  16.      }  
  17.      public static void listDemo()  
  18.      {  
  19.           File f = new File("D:\\learn\\day19");  
  20.           //调用list方法的file对象封装的必须是一个目录,并且存在.  
  21.           String[] names = f.list(new MyFilenameFileter());//传进一个过滤器  
  22.           for(String s : names)  
  23.           {  
  24.                System.out.println(s);  
  25.           }  
  26.      }  
  27.   
  28.      public static void listRootsDemo()  
  29.      {  
  30.           //列出电脑中有效的盘符  
  31.           File[] files = File.listRoots();  
  32.   
  33.           for(File f : files)  
  34.           {  
  35.                System.out.println(f);  
  36.           }  
  37.      }  
  38. }  
  39.   
  40. //定义一个过滤器  
  41. class MyFilenameFileter implements FilenameFilter  
  42. {      
  43.      public boolean accept(File dir,String name)  
  44.      {  
  45.           return name.endsWith(".class");  
  46.      }  
  47. }  

递归--列出目录下所有内容


[java] view plaincopy
  1. /* 
  2. 列出指定目录下文件或者文件夹,包含子目录中的内容. 
  3. 也就是列出指定目录下所有内容. 
  4.  
  5. 因为目录中还有目录,只要使用同一个列出目录功能的函数完成即可. 
  6. 在列出过程中出现的还是目录的话,还可以再次调用本功能. 
  7. 也就是函数自身调用自身. 
  8. 这种表现形式,或者变成手法,称为递归. 
  9.  
  10. 递归要注意的: 
  11.  
  12. 1.一定要限定条件 
  13.  
  14. 2.要注意递归的次数,尽量避免内存溢出. 
  15. */  
  16. import java.io.*;  
  17. class FileDemo3  
  18. {  
  19.      public static void main(String[] args)  
  20.      {  
  21.           File f = new File("d:\\learn");  
  22.           //showDir(f);  
  23.           //toBin(6);  
  24.           System.out.println(getSum(10));  
  25.      }  
  26.      public static int getSum(int n)  
  27.      {  
  28.           if (n==1)  
  29.                return 1;  
  30.           else  
  31.                return n+getSum(n-1);  
  32.   
  33.      }  
  34.      public static void toBin(int n)  
  35.      {  
  36.           if (n>0)  
  37.           {  
  38.                toBin(n/2);  
  39.                System.out.print(n%2);  
  40.           }  
  41.      }  
  42.      public static void showDir(File dir)  
  43.      {  
  44.           System.out.println(dir);  
  45.           File[] files = dir.listFiles();  
  46.           for(int x= 0; x<files.length; x++)  
  47.           {  
  48.                if(files[x].isDirectory())  
  49.                     showDir(files[x]);  
  50.                else  
  51.                     System.out.println(files[x]);  
  52.           }  
  53.      }  
  54. }  

列出目录下所有内容--带层级


[java] view plaincopy
  1. import java.io.*;  
  2. class FileDemo4  
  3. {  
  4.      public static void main(String[] args)  
  5.      {  
  6.           File f = new File("d:\\learn");  
  7.           showDir(f,0);  
  8.      }  
  9.      //定义一个层级方法  
  10.      public static String getLevel(int level)  
  11.      {  
  12.           StringBuilder sb = new StringBuilder();  
  13.           for (int x = 1; x<level; x++)  
  14.           {  
  15.                sb.append("    ");  
  16.           }  
  17.           return sb.toString();  
  18.      }  
  19.      public static void showDir(File dir,int level)  
  20.      {  
  21.           System.out.println(getLevel(level)+dir);  
  22.           level++;  
  23.           File[] files = dir.listFiles();  
  24.           for(int x= 0; x<files.length; x++)  
  25.           {  
  26.                if(files[x].isDirectory())  
  27.                     showDir(files[x],level);  
  28.                else  
  29.                     System.out.println(getLevel(level)+files[x]);  
  30.           }  
  31.      }  
  32. }  

删除带内容的目录

[java] view plaincopy
  1. import java.io.*;  
  2. /* 
  3. 删除原理: 
  4. 在windows中,删除目录是从里面往外删除的. 
  5.  
  6. 既然是从里面往外删除,就需要用到递归. 
  7. */  
  8. class RemoveDir  
  9. {  
  10.      public static void main(String[] args)  
  11.      {  
  12.           File dir = new File("d:\\新建文件夹");  
  13.           removeDir(dir);  
  14.      }  
  15.   
  16.      public static void removeDir(File dir)  
  17.      {  
  18.           File [] files = dir.listFiles();  
  19.           for (int x=0; x<files.length; x++ )  
  20.           {  
  21.                if(files[x].isDirectory())  
  22.                     removeDir(files[x]);  
  23.                else  
  24.                     System.out.println(files[x]+"--file--"+files[x].delete());  
  25.           }  
  26.           System.out.println(dir+"==dir=="+dir.delete());  
  27.      }  
  28. }  

创建java文件列表

[java] view plaincopy
  1. /* 
  2. 练习 
  3. 将一个指定目录下的java文件的绝对路径,存储到一个文本文件中 
  4. 建立一个java文件列表文件. 
  5.  
  6. 思路: 
  7. 1.对指定的目录进行递归. 
  8. 2.获取递归过程所有的java文件路径 
  9. 3.将这些路径存储到集合中. 
  10. 4.将集合中的数据写入到一个文件中 
  11. */  
  12. import java.io.*;  
  13. import java.util.*;  
  14. class JavaFileList  
  15. {  
  16.      public static void main(String[] args) throws IOException  
  17.      {  
  18.           File dir = new File("d:\\learn");  
  19.           List<File> list = new ArrayList<File>();  
  20.           fileToList(dir,list);  
  21.           File file = new File(dir,"javalist.txt");  
  22.           writeTOFile(list,file);  
  23.      }  
  24.      public static void fileToList(File dir,List<File> list)  
  25.      {  
  26.           File[] files = dir.listFiles();  
  27.           for (File f : files )  
  28.           {  
  29.                if (f.isDirectory())  
  30.                     fileToList(f,list);  
  31.                else  
  32.                {  
  33.                     if(f.getName().endsWith(".java"));  
  34.                          list.add(f);  
  35.                }  
  36.           }  
  37.      }  
  38.      public static void writeTOFile(List<File> list,File file)throws IOException  
  39.      {  
  40.           BufferedWriter bw = new BufferedWriter(new FileWriter(file));  
  41.           for (File f : list )  
  42.           {  
  43.                bw.write(f.getAbsolutePath());  
  44.                bw.newLine();  
  45.                bw.flush();  
  46.           }  
  47.      }  
  48. }  

Properties类

Properties是hashtable的子类.

也就是说它具备map集合的特点.而且它里面存储的键值对都是字符串.

是集合中和IO技术相集合的集合容器.

该对象的特点:可以用于键值对形式的配置文件

那么在加载数据时,需要数据有固定格式:键=值;

[java] view plaincopy
  1. import java.io.*;  
  2. import java.util.*;  
  3. import java.util.*;  
  4. class PropertiesDemo  
  5. {  
  6.      public static void main(String[] args) throws IOException  
  7.      {  
  8.           //setAndget();  
  9.           //method_1();  
  10.           loadDemo();  
  11.      }  
  12.      //Properties中提供了load方法来完成method_1  
  13.      public static void loadDemo() throws IOException  
  14.      {  
  15.           Properties prop = new Properties();  
  16.           FileInputStream fis = new FileInputStream("c:\\info.txt");  
  17.           prop.load(fis);  
  18.           prop.setProperty("zhangsan","88");  
  19.           FileOutputStream fos = new FileOutputStream("c:\\info.txt");  
  20.           prop.store(fos,"haha");  
  21.           prop.list(System.out);  
  22.           fis.close();  
  23.           fos.close();  
  24.      }  
  25.   
  26.      //演示,如何将流中的数据存储到集合中.  
  27.      //想要将info.txt中键值数据存到集合中进行操作.  
  28.      /* 
  29.           1.用一个流和info.txt文件关联. 
  30.           2.读取一个数据,将该数据用"="进行切割 
  31.           3.等号左面作为键,右边作为值.存入到Properties集合中即可 
  32.      */  
  33.      public static void method_1() throws IOException  
  34.      {  
  35.           BufferedReader br = new BufferedReader(new FileReader("c:\\info.txt"));  
  36.           Properties prop = new Properties();  
  37.           String line = null;  
  38.           while ((line=br.readLine())!=null)  
  39.           {  
  40.                String[] arr = line.split("=");  
  41.                prop.setProperty(arr[0],arr[1]);  
  42.           }  
  43.           br.close();  
  44.           System.out.println(prop);  
  45.      }  
  46.   
  47.      //设置和获取元素.  
  48.      public static void setAndget()  
  49.      {  
  50.           Properties prop = new Properties();  
  51.           prop.setProperty("zhangsan","39");  
  52.           prop.setProperty("lisi","47");  
  53.   
  54.           System.out.println(prop);  
  55.           System.out.println(prop.getProperty("lisi"));  
  56.            
  57.           prop.setProperty("lisi",90+"");  
  58.   
  59.           Set<String> names = prop.stringPropertyNames();  
  60.           for (String s : names)  
  61.           {  
  62.                System.out.println(s+":"+prop.getProperty(s));  
  63.           }  
  64.   
  65.      }  
  66. }  

Properties练习--限定程序执行次数

[java] view plaincopy
  1. import java.io.*;  
  2. import java.util.*;  
  3. /* 
  4. 用于记录应用程序运行次数. 
  5. 如果使用次数已到,那么给出注册提示. 
  6.  
  7. 很容易想到的是:计数器. 
  8. 开始该计数器定义在程序中,随着程序的运行而存在的内存中,并进行字增 
  9. 可是随着该应用程序的推出,该计数器也在内存中消失了. 
  10.  
  11. 下一次在启动该程序,又重新开始从0计数 
  12. 这样就不是我们想要的. 
  13.  
  14. 程序即使结束,该计数器的值也存在. 
  15. 下次程序启动会先家在该计数器的值并加1后在重新存储起来. 
  16.  
  17. 所以要建立一个配置文件,用于记录该软件的使用次数. 
  18.  
  19. 该配置文件使用键值对的形式. 
  20. 这样便于阅读数据,并操作数据. 
  21.  
  22. 键值对数据是map集合 
  23. 数据是以文件形式存储,用到IO技术. 
  24. 那么map-->Properties + IO 
  25.  
  26. 配置文件可以实现应用程序数据的共享. 
  27.  
  28. 1.创建有给读取流关联配置文件 
  29. */  
  30. class  RunCount  
  31. {  
  32.      public static void main(String[] args) throws IOException  
  33.      {  
  34.           File file = new File("c:\\property.ini");  
  35.           if(!file.exists())  
  36.                file.createNewFile();  
  37.           Properties prop = new Properties();  
  38.           FileInputStream fr = new FileInputStream(file);  
  39.           prop.load(fr);  
  40.           String value = prop.getProperty("count");  
  41.           if(value==null)  
  42.                prop.put("count","1");  
  43.           else  
  44.           {  
  45.                System.out.println(value);  
  46.                int count = Integer.parseInt(value);  
  47.                if(count>=5)  
  48.                {  
  49.                     System.out.println("您的使用次数已到");  
  50.                     return;  
  51.                }  
  52.                count++;  
  53.                prop.setProperty("count",count+"");  
  54.           }  
  55.           FileOutputStream fw = new FileOutputStream(file);//输出流会覆盖原文件  
  56.           prop.store(fw,"test");  
  57.           fr.close();  
  58.           fw.close();  
  59.      }  
  60. }  

打印流PrintWriter和PrintStream

打印流:

该流提供了打印方法,可以将各种数据类型的数据都原样打印.

字节打印流

PrintStream

构造函数可以接收的参数类型.

1.File对象.File

2.字符串路径.String

3.字节输出流.OutputStream

字符打印流

PrintWriter(常用)

构造函数可以接收的参数类型

1.File对象.File

2.字符串路径.String

3.字节输出流.OutputStream

4.字符输出流.Writer

[java] view plaincopy
  1. import java.io.*;  
  2.   
  3. class  PrintStreamDemo  
  4. {  
  5.      public static void main(String[] args) throws IOException  
  6.      {  
  7.           BufferedReader br =  
  8.                new BufferedReader(new InputStreamReader(System.in));  
  9.           PrintWriter pw =  
  10.                new PrintWriter(new FileWriter("c:\\demo.txt"),true);//可实现自动刷新  
  11.           String line = null;  
  12.           while ((line=br.readLine())!=null)  
  13.           {  
  14.                if(line.equals("over"))  
  15.                     break;  
  16.                pw.println(line.toUpperCase());  
  17.           }  
  18.           br.close();  
  19.           pw.close();  
  20.      }  
  21. }  

序列合并流

SequenceInputStream是能对多个流进行合并成一个读取流,它在构造时需要传入Enumeration,而这个只用Vector中有,所以这个多个读取流要加入Vector集合中。注意:它只是对读取流进行合并。

它使用步骤:

1.创建Vector<InputStream>

2.将要合并的InputStream加入Vector

3.通过Vector获取Enumeration

4.创建SequenceInputStream,将Enumeration作为参数传入。

[java] view plaincopy
  1. import java.io.*;  
  2. import java.util.*;  
  3. class SequenceDemo  
  4. {  
  5.      public static void main(String[] args) throws IOException  
  6.      {  
  7.           Vector<FileInputStream> v = new Vector<FileInputStream>();  
  8.           v.add(new FileInputStream("c:\\1.txt"));  
  9.           v.add(new FileInputStream("c:\\2.txt"));  
  10.           v.add(new FileInputStream("c:\\3.txt"));  
  11.           Enumeration<FileInputStream> e = v.elements();  
  12.   
  13.           SequenceInputStream sis = new SequenceInputStream(e);  
  14.           FileOutputStream fos = new FileOutputStream("c:\\4.txt");  
  15.   
  16.           byte[] bys = new byte[1024];  
  17.           int len = 0;  
  18.           while ((len = sis.read(bys))!=-1)  
  19.           {  
  20.                fos.write(bys,0,len);  
  21.           }  
  22.           fos.close();  
  23.           sis.close();  
  24.      }  
  25. }  

文件的切割和合并

[java] view plaincopy
  1. import java.io.*;  
  2. import java.util.*;  
  3. class SplitFile  
  4. {  
  5.      public static void main(String[] args) throws IOException  
  6.      {  
  7.           //splitFile();  
  8.           merge();  
  9.      }  
  10.      //合并  
  11.      public static void merge() throws IOException  
  12.      {  
  13.           ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();  
  14.           al.add(new FileInputStream("c:\\2.part"));  
  15.           al.add(new FileInputStream("c:\\3.part"));  
  16.           al.add(new FileInputStream("c:\\4.part"));  
  17.           final Iterator<FileInputStream> it = al.iterator();  
  18.           Enumeration<FileInputStream> en = new Enumeration<FileInputStream>()  
  19.           {  
  20.                public boolean hasMoreElements()  
  21.                {  
  22.                     return it.hasNext();  
  23.                }  
  24.                public FileInputStream nextElement()  
  25.                {  
  26.                     return it.next();  
  27.                }  
  28.           };  
  29.           SequenceInputStream sis = new SequenceInputStream(en);  
  30.           FileOutputStream fos = new FileOutputStream("c:\\0.jpg");  
  31.           byte[] bys = new byte[1024];  
  32.           int len = 0;  
  33.           while ((len=sis.read(bys))!=-1)  
  34.           {  
  35.                fos.write(bys,0,len);  
  36.           }  
  37.           sis.close();  
  38.           fos.close();  
  39.      }  
  40.     //切割  
  41.      public static void splitFile() throws IOException  
  42.      {  
  43.           FileInputStream fis = new FileInputStream("c:\\1.jpg");  
  44.           FileOutputStream fos = null;  
  45.           byte[] bys = new byte[1024*50];  
  46.           int len = 0;  
  47.           int count = 2;  
  48.           while ((len=fis.read(bys))!=-1)  
  49.           {  
  50.                fos = new FileOutputStream("c:\\"+(count++)+".part");  
  51.                fos.write(bys,0,len);  
  52.                fos.close();  
  53.           }  
  54.           fis.close();  
  55.      }  
  56. }  

对象序列化:

被序列化的类必须实现Serializable接口,来获得ID.

也可以自己设置ID,例如:static final long serialVersionUID = 42L

static静态成员是不能被序列化的.

transient修饰的成员也是不能被序列化的

[java] view plaincopy
  1. import java.io.*;  
  2. class ObjectStreamDemo  
  3. {  
  4.      public static void main(String[] args) throws Exception  
  5.      {  
  6.           //writeObj();  
  7.           readObj();  
  8.      }  
  9.      public static void readObj() throws Exception  
  10.      {  
  11.           ObjectInputStream ois =  
  12.                new ObjectInputStream(new FileInputStream("obj.txt"));  
  13.           Person p = (Person)ois.readObject();  
  14.           System.out.println(p);  
  15.           ois.close();  
  16.      }  
  17.      public static void writeObj() throws IOException  
  18.      {  
  19.           ObjectOutputStream oos =  
  20.                new ObjectOutputStream(new FileOutputStream("obj.txt"));  
  21.           oos.writeObject(new Person("lisi",97));  
  22.           oos.close();  
  23.      }  
  24. }  
  25. class Person implements Serializable  
  26. {  
  27.      //给类设置ID,  
  28.      public static final long serialVersionUID = 42L;  
  29.      String name;  
  30.      int age;  
  31.      Person(String name,int age)  
  32.      {  
  33.           this.name = name;  
  34.           this.age = age;  
  35.      }  
  36.      public String toString()  
  37.      {  
  38.           return name+":"+age;  
  39.      }  
  40. }  

管道流:输入输出可以直接连接,结合线程使用.

     |--管道输入流:PipedInputStream

     |--管道输出流:PipedOutpuStream

[java] view plaincopy
  1. import java.io.*;  
  2. class Read implements Runnable  
  3. {  
  4.      private PipedInputStream in;  
  5.      Read(PipedInputStream in)  
  6.      {  
  7.           this.in=in;  
  8.      }  
  9.      public void run()  
  10.      {  
  11.           try  
  12.           {  
  13.                byte[] bys = new byte[1024];  
  14.                System.out.println("读取前..没有数据..进入阻塞状态");  
  15.                int len = in.read(bys);  
  16.                System.out.println("读取到数据..阻塞状态结束");  
  17.                String s = new String(bys,0,len);  
  18.                System.out.println(s);  
  19.                in.close();  
  20.           }  
  21.           catch (IOException e)  
  22.           {  
  23.                throw new RuntimeException("管道读取流失败");  
  24.           }  
  25.      }  
  26. }  
  27. class Write implements Runnable  
  28. {  
  29.      private PipedOutputStream out;  
  30.      Write(PipedOutputStream out)  
  31.      {  
  32.           this.out = out;  
  33.      }  
  34.      public void run()  
  35.      {  
  36.           try  
  37.           {  
  38.                System.out.println("开始写入数据,等待6秒");  
  39.                Thread.sleep(6000);  
  40.                out.write("PipedOutputStream is coming".getBytes());  
  41.                out.close();  
  42.           }  
  43.           catch (Exception e)  
  44.           {  
  45.                throw new RuntimeException("管道输出流失败");  
  46.           }  
  47.      }  
  48. }  
  49. class  PipedStreamDemo  
  50. {  
  51.      public static void main(String[] args) throws IOException  
  52.      {  
  53.           PipedInputStream in = new PipedInputStream();  
  54.           PipedOutputStream out = new PipedOutputStream();  
  55.           in.connect(out);  
  56.           new Thread(new Read(in)).start();  
  57.           new Thread(new Write(out)).start();  
  58.      }  
  59. }  

随机读写RandomAccessFile

该类不算是IO体系中的子类.

而是直接继承自Object.

但是它是IO包的成员,因为它具备读和写功能.

内部封装了一个byte数组,而且通过指针对数组的元素进行操作.

可以通过getFilePointer获取指针位置.

同时可以通过seek改变指针的位置

其实完成读写的原理就是内部封装了字节输入流和输出流.

通过构造函数可以看出,该类只能操作文件.

而且操作的文件还需要指定权限.

如果模式为只读 r,则不会创建文件,回去读取一个已存在的文件,如果该文件不存在,会出现异常

如果模式为 rw,操作的文件不存在,会自动创建,如果存在则不会覆盖

[java] view plaincopy
  1. class RandomAccessFileDemo  
  2. {  
  3.      public static void main(String[] args) throws IOException  
  4.      {  
  5.           //writeFile();  
  6.           //readFile();  
  7.           writeFile_2();  
  8.      }  
  9.       
  10.      public static void readFile() throws IOException  
  11.      {  
  12.           RandomAccessFile raf = new RandomAccessFile("ran.txt","r");  
  13.           //用seek()方法把指针调到8位置上  
  14.           //raf.seek(8);  
  15.   
  16.           //跳过指定的字节数,skipBytes()只能向前,不能后退  
  17.           raf.skipBytes(8);  
  18.   
  19.           byte[] bys = new byte[4];  
  20.           raf.read(bys);  
  21.           String name = new String(bys);  
  22.   
  23.           //方法readInt()取一个32位的整数  
  24.           int age = raf.readInt();  
  25.            
  26.           System.out.println("name="+name);  
  27.           System.out.println("age="+age);  
  28.      }  
  29.      public static void writeFile_2()throws IOException  
  30.      {  
  31.           RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");  
  32.           raf.seek(16);//利用seek方法,可以实现指定位置数据的添加和修改  
  33.           raf.write("周七".getBytes());  
  34.           raf.writeInt(103);  
  35.   
  36.      }  
  37.      public static void writeFile() throws IOException  
  38.      {  
  39.           RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");  
  40.           raf.write("李四".getBytes());  
  41.           raf.writeInt(97);  
  42.           raf.write("王五".getBytes());  
  43.           raf.writeInt(99);  
  44.           raf.close();  
  45.      }           
  46. }  

操作[基本数据类型]的流对象

可以用于操作基本数据类型的数据的流对象,按照输入输出分为DataInputStreamDataOutputStream。这两个类提供了对8种基本数据类型的写入和读取的方法。

此外,它们有对应的wirtUTF-8(String str)readUTF-8()方法,来支持按照UTF-8修改版编码(与UTF-8稍有不同)来写入和读取字符串。

[java] view plaincopy
  1. <pre name="code" class="java">import java.io.*;  
  2. class  DataStreamDemo  
  3. {  
  4.      public static void main(String[] args) throws IOException  
  5.      {  
  6.           //writeData();  
  7.           //readData();  
  8.           //writeUtf();  
  9.           readUtf();  
  10.      }  
  11.   
  12.      public static void readUtf() throws IOException  
  13.      {  
  14.           DataInputStream dis =  
  15.                new DataInputStream(new FileInputStream("utfdat.txt"));  
  16.   
  17.           System.out.println(dis.readUTF());  
  18.           dis.close();  
  19.      }  
  20.   
  21.      public static void writeUtf() throws IOException  
  22.      {  
  23.           DataOutputStream dos =  
  24.                new DataOutputStream(new FileOutputStream("utfdat.txt"));  
  25.           dos.writeUTF("你好");  
  26.           dos.close();  
  27.      }  
  28.       
  29.      public static void readData() throws IOException  
  30.      {  
  31.           DataInputStream dis =  
  32.                new DataInputStream(new FileInputStream("data.txt"));  
  33.   
  34.           System.out.println("b="+dis.readInt());  
  35.           boolean b = dis.readBoolean();  
  36.           double d = dis.readDouble();  
  37.           System.out.println("b="+b+"\r\n"+"d="+d);  
  38.           dis.close();  
  39.      }  
  40.   
  41.      public static void writeData() throws IOException  
  42.      {  
  43.           DataOutputStream dos =  
  44.                new DataOutputStream(new FileOutputStream("data.txt"));  
  45.   
  46.           dos.writeInt(234);  
  47.           dos.writeBoolean(true);  
  48.           dos.writeDouble(9887.543);  
  49.           dos.close();  
  50.      }  
  51. }  
  52. </pre>  
  53. <pre></pre>  
  54. <p></p>  
  55. <pre></pre>  
  56. <div>  
  57. <p>操<span style="font-family:宋体">作字节数组</span><span style="font-family:宋体">的流对象</span></p>  
  58. <p>按输入输出分为两个类</p>  
  59. <p>ByteArrayInputStream<span style="font-family:宋体">:在构造的时候,需要接受数据源,而且这个数据源是一个字符数组。</span></p>  
  60. <p>ByteArrayOutputStream<span style="font-family:宋体">:在构造的时候,不需要定义目的地,因为该对象内部已经封装了可变长度的字节数组,它就是目的地;它对外提供了</span><span style="font-family:Times New Roman">toString()</span><span style="font-family:宋体">方法,可以把内部封装的字节数组按照默认的字符集或指定的字符集以字符串的形式返回。</span></p>  
  61. <p>注意:</p>  
  62. <p>1.<span style="font-family:宋体">因为这两个流对象都操作的是数组,并没有使用系统资源,所以,不用进行</span><span style="font-family:Times New Roman">close</span><span style="font-family:宋体">关闭,即使你关闭了,它的其他方法还可以使用,而不会抛出</span><span style="font-family:Times New Roman">IOException</span><span style="font-family:宋体">。</span></p>  
  63. <p>2.<span style="font-family:宋体">使用这对对象操作时,它的源和目的都是内存。</span></p>  
  64. <p>用途:这两个对象是在用流的思想来操作数组,当我们需要把一个文件中的数据加入内存中的数组时,就可以考虑用这个两个对象。此外,它还有<span style="font-family:Times New Roman">writeTo</span><span style="font-family:宋体">(</span><span style="font-family:Times New Roman">OutputStream os</span><span style="font-family:宋体">)可以把</span><span style="font-family:Times New Roman">ByteArrayOutputStream</span><span style="font-family:宋体">对象内部定义的缓冲区内容,一次性写入</span><span style="font-family:Times New Roman">os</span><span style="font-family:宋体">中。</span></p>  
  65. <p>操作字符数组、字符串的流对象类型与之相似,可以参与它们的使用方法。</p>  
  66. <p></p>  
  67. <pre name="code" class="java">/* 
  68. 用于操作字节数组的流对象, 
  69.  
  70. ByteArrayInputStream:在构造的时候,需要接收数据源,而且数据源是一个字节数组. 
  71.  
  72. ByteArrayOutputStream:在构造的时候,不用定义目的,因为该对象中已经 
  73.                                                             封装了可变长度的字节数组. 
  74. (CharArrayReader CharArrayWriter)功能和用法基本相同 
  75. (StringReader StringWiter)功能和用法基本相同 
  76.  
  77. 因为这两个流对象操作的都是数组,并没有使用系统资源. 
  78. 所以,不用进行close关闭资源. 
  79.  
  80. 在流操作规律讲解时: 
  81.  
  82. 源设备: 
  83.      键盘 System.in, 硬盘 FileInputStream, 内存 ArrayInputStream 
  84. 目的设备 
  85.      控制台 System.out, 硬盘 FileOutputStream, 内存 ArrayOutputStream 
  86.  
  87. 用流的读写思想操作数组. 
  88. */  
  89. import java.io.*;  
  90. class  ByteArrayStream  
  91. {  
  92.      public static void main(String[] args) throws IOException  
  93.      {  
  94.           //数据源.  
  95.           ByteArrayInputStream bis = new ByteArrayInputStream("ABCDEF".getBytes());  
  96.   
  97.           //数据目的  
  98.           ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  99.   
  100.           int by = 0;  
  101.           while ((by=bis.read())!=-1)  
  102.           {  
  103.                bos.write(by);  
  104.           }  
  105.           System.out.println(bos.size());  
  106.           System.out.println(bos.toString());  
  107.   
  108.           bos.writeTo(new FileOutputStream("a.txt"));//只有writeTO()方法需要抛出异常  
  109.      }  
  110. }  
  111.   
  112.           dos.writeBoolean(true);  
  113.           dos.writeDouble(9887.543);  
  114.           dos.close();  
  115.      }  
  116. }</pre><br>  
  117. <p></p>  
  118. <div>  
  119. <p>编码问题 <br>  
  120. </p>  
  121. <p>字符流的出现是为了方便操作字符数据,其方法操作的原因是因为内部加入了编码表。<span style="font-family:Times New Roman">Java</span><span style="font-family:宋体">中能够实现字节根据指定编码表转成字符的,有四个类:</span><span style="font-family:Times New Roman">InputStreamReader</span><span style="font-family:宋体">和</span><span style="font-family:Times New Roman">OutputStreamWriter</span><span style="font-family:宋体">,</span><span style="font-family:Times New Roman">PrintStream</span><span style="font-family:宋体">和</span><span style="font-family:Times New Roman">PrintWriter</span><span style="font-family:宋体">。它们都能够加构造时,指定编码表;但后两个是打印流,只能用于打印,使用有局限,所以相对而言,还是前两个转换流使用多一些。</span></p>  
  122. <p>编码表的由来</p>  
  123. <p>计算机只能识别二进制数据,早期是电信号。为了应用计算机方便,让它可以识别各个国家的文字,就将各个国家的文字用数字来表示,并将文字与二进制数字一一对应,形成了一张表,这个表就是编码表。</p>  
  124. <p>常见的编码表</p>  
  125. <p>地域码表</p>  
  126. <p>1.ASCII<span style="font-family:宋体">:美国码表,息交换码,用一个字节的</span><span style="font-family:Times New Roman">7</span><span style="font-family:宋体">位表示。</span></p>  
  127. <p>2.ISO8859-1<span style="font-family:宋体">:欧洲码表,拉丁码表,用一个字节的</span><span style="font-family:Times New Roman">8</span><span style="font-family:宋体">位表示,最高位</span><span style="font-family:Times New Roman">1</span></p>  
  128. <p>3.GB2312<span style="font-family:宋体">:中国中文编码表,它用两个字节表示,为兼容</span><span style="font-family:Times New Roman">ASCII</span><span style="font-family:宋体">,它的两个字节的高位都是</span><span style="font-family:Times New Roman">1</span><span style="font-family:宋体">,也即是两个负数;但与</span><span style="font-family:Times New Roman">ISO8859-1</span><span style="font-family:宋体">冲突。大概有六七千个字。</span></p>  
  129. <p>4.GBK<span style="font-family:宋体">:中国的中文编码表的升级版,扩容到</span><span style="font-family:Times New Roman">2</span><span style="font-family:宋体">万多字。</span></p>  
  130. <p>通用码表:</p>  
  131. <p>1.Unicode<span style="font-family:宋体">:国际标准码,融合多种语言文字。所有的文字都用两个字节表示,</span><span style="font-family:Times New Roman">Java</span><span style="font-family:宋体">默认使用的就是</span><span style="font-family:Times New Roman">Unicode</span><span style="font-family:宋体">。</span></p>  
  132. <p>2.UTF-8<span style="font-family:宋体">:</span><span style="font-family:Times New Roman">UnicodeTransform Format -8</span><span style="font-family:宋体">。</span><span style="font-family:Times New Roman">Unicode</span><span style="font-family:宋体">码把用一个字节能装下的文字,也用两个字节表示,有些浪费空间,对之进行优化的结果就是</span><span style="font-family:Times New Roman">UTF-8</span><span style="font-family:宋体">。</span></p>  
  133. <p>UTF-8<span style="font-family:宋体">编码表,一个文字最用一个字节表示,最多用</span><span style="font-family:Times New Roman">3</span><span style="font-family:宋体">个字节表示,并且每个字节开始都有标识头,所以很容易于其他编码表区分出来。</span></p>  
  134. </div>  
  135. <pre name="code" class="java">//转换流的字符编码使用  
  136. import java.io.*;  
  137. class  EncodeStream  
  138. {  
  139.      public static void main(String[] args) throws IOException  
  140.      {  
  141.           writeText();  
  142.           readText();  
  143.      }  
  144.      public static void readText() throws IOException  
  145.      {  
  146.           InputStreamReader isr =  
  147.                new InputStreamReader(new FileInputStream("gbk.txt"),"UTF-8");  
  148.           char[] buf = new char[10];  
  149.           int len = isr.read(buf);  
  150.           String s = new String(buf,0,len);  
  151.           System.out.println(s);  
  152.           isr.close();  
  153.      }  
  154.       
  155.      public static void writeText() throws IOException  
  156.      {  
  157.           OutputStreamWriter osw =  
  158.                new OutputStreamWriter(new FileOutputStream("gbk.txt","UTF-8"));  
  159.           osw.write("你好");  
  160.           osw.close();  
  161.      }  
  162. }</pre><br>  
  163. <div>  
  164. <p>编码问题的产生与解决</p>  
  165. <p>从上边的那些编码表可以看出,<span style="font-family:Times New Roman">GBK</span><span style="font-family:宋体">和</span><span style="font-family:Times New Roman">Unicode</span><span style="font-family:宋体">都能识别中文,那么当一台电脑使用</span><span style="font-family:Times New Roman">GBK</span><span style="font-family:宋体">,而另一台电脑使用</span><span style="font-family:Times New Roman">Unicode</span><span style="font-family:宋体">时,虽然在各自的电脑上都能识别中文,但他们其中一方向另一方发送中文文字时,另一方却不能识别,出现了乱码。这是因为</span><span style="font-family:Times New Roman">GBK</span><span style="font-family:宋体">和</span><span style="font-family:Times New Roman">Unicode</span><span style="font-family:宋体">虽然都能识别中文,但对同一个中文文字,他们在两个编码表对应的编码值不同。这时,在解读别人传来的中文数据时,就需要指定解析中文使用的编码表了。</span></p>  
  166. <p>而转换流就能指定编码表,它的应用可以分为:</p>  
  167. <p>1.      <span style="font-family:宋体">可以将字符以指定的编码格式存储。</span></p>  
  168. <p>2.      <span style="font-family:宋体">可以对文本数据以指定的编码格式进行解读。</span></p>  
  169. <p>它们指定编码表的动作是由构造函数完成的。</p>  
  170. <p>编码:字符串变成字节数组,<span style="font-family:Times New Roman">String to byte[]</span><span style="font-family:宋体">,使用</span><span style="font-family:Times New Roman">str.getBytes(charsetName)</span><span style="font-family:宋体">;</span></p>  
  171. <p>解码:字节数组变成字符串,<span style="font-family:Times New Roman">byte[] to String</span><span style="font-family:宋体">,使用</span><span style="font-family:Times New Roman">new String(byte[] b, charsetName);</span></p>  
  172. <p>编码编错:是指你对一个文字进行编码时,使用了不识别该文字的编码表,比如你编码一个汉字,却使用了<span style="font-family:Times New Roman">ISO8859-1</span><span style="font-family:宋体">这个拉丁码表,</span><span style="font-family:Times New Roman">ISO8859-1</span><span style="font-family:宋体">根本就不识别汉字。编码编错时,你用任何方式对编码后的数据进行处理,都不可能再拿到这个汉字了。</span></p>  
  173. <p>解码解错:是指你对一个文字进行编码事,使用了正确的码表,编码正确,但在解码时使用了错误的码表,那么你还有可能拿到这个文字。这分为两种情况:</p>  
  174. <p>第一种情况:你使用的是<span style="font-family:Times New Roman">GBK</span><span style="font-family:宋体">编码,解码时用的是</span><span style="font-family:Times New Roman">ISO8859-1</span><span style="font-family:宋体">,因为</span><span style="font-family:Times New Roman">GBK</span><span style="font-family:宋体">编译一个汉字,使用两个字节,</span><span style="font-family:Times New Roman">ISO8859-1</span><span style="font-family:宋体">解码时是一个字节一个字节读取,虽然解码出现了乱码,但是这个汉字的二进制数据没有变化,那么你可以通过再次编译获取其原来的二进制数据,然后再次使用</span><span style="font-family:Times New Roman">GBK</span><span style="font-family:宋体">编码,解码成功。</span></p>  
  175. <p>第二种情况:你使用的是<span style="font-family:Times New Roman">GBK</span><span style="font-family:宋体">编码,解码时用的却是</span><span style="font-family:Times New Roman">UTF-8</span><span style="font-family:宋体">,因为这两个码表都识别汉字,那么你再次使用</span><span style="font-family:Times New Roman">UTF-8</span><span style="font-family:宋体">编码时,就有可能把一个汉字的</span><span style="font-family:Times New Roman">2</span><span style="font-family:宋体">个字节,变成</span><span style="font-family:Times New Roman">3</span><span style="font-family:宋体">个,这时再用</span><span style="font-family:Times New Roman">GBK</span><span style="font-family:宋体">解码时,得到的仍然是乱码,解码仍然失败。</span></p>  
  176. </div>  
  177. <pre name="code" class="java">/* 
  178. 编码:字符串变字节数组; 
  179.  
  180. 解码:字节数组变字符串; 
  181.  
  182. String --> byte[]: str.getBytes(码表); 
  183.  
  184. byte[] --> String: new String(byte[],码表); 
  185.  
  186. 注意:GBK和UTF-8是不能编码解码的. 
  187. */  
  188. import java.util.*;  
  189. class  EncodeDemo  
  190. {  
  191.      public static void main(String[] args) throws Exception  
  192.      {  
  193.           String s = "你好";  
  194.   
  195.           byte[] bys = s.getBytes("GBK");  
  196.           System.out.println(Arrays.toString(bys));  
  197.   
  198.           String s1 = new String(bys,"iso8859-1");  
  199.           System.out.println(s1);  
  200.   
  201.           byte[] buf = s1.getBytes("iso8859-1");  
  202.           System.out.println(Arrays.toString(buf));  
  203.   
  204.           String s2 = new String(buf,"GBK");  
  205.           System.out.println(s2);  
  206.      }  
  207. }</pre><br>  
  208. <p></p>  
  209. <p>“联通”的编码问题</p>  
  210. <p>问题描述:打开记事本仅写入“联通”两个汉字,关闭后,再次打开会出现乱码。</p>  
  211. <p></p>  
  212. <pre name="code" class="java">class EncodeDemo2     
  213. {    
  214.     public static void main(String[] args) throws Exception    
  215.     {    
  216.         String s = "联通";    
  217.         byte [] by = s.getBytes("GBK");    
  218.         for(byte b:by)    
  219.         {    
  220.             System.out.println(Integer.toBinaryString(b&255));    
  221.         /*    
  222.          * “联通”编码问题的原因:  
  223.          //boBinaryString(int)它接受的是int,byte类型的b参与运算时会类型提升为int,我们需要的是提升后的低8位,所以&255  
  224.               
  225.              对联通的结果进行GBK编码时,其二进制码为:  
  226.             11000001  
  227.             10101010  
  228.             11001101  
  229.             10101000   
  230.              编码的结果符合UTF-8的格式,所以再次打开记事本时,它会把它按照UTF-8的格式进行解码,结果就是两个乱码。  
  231.         */    
  232.         }    
  233.     }    
  234. }</pre><br>  
  235. IO流练习  
  236. <p></p>  
  237. <p></p>  
  238. <pre name="code" class="java">/* 
  239. 有五个学生,每个学生有3门课的成绩, 
  240. 从键盘输入以上数据(包括姓名,三门课成绩) 
  241. 输入的格式:如:zhang,30,40,60,并计算出总成绩. 
  242. 并把学生的信息按照计算出的总分高低顺序存放在文件"stud.txt"中 
  243.  
  244. 1.描述学生对象. 
  245. 2.定义一个操作学生对象的工具类. 
  246.  
  247. 思想: 
  248. 1.通过键盘录入一行数据,并将该行中的信息取出封装成学生对象. 
  249. 2.因为学生有很多,那么需要存储,使用到集合,因为要对学生总分进行排序. 
  250.      所以可以使用TreeSet. 
  251. 3.将集合的信息写入到一个文件中. 
  252. */  
  253. import java.io.*;  
  254. import java.util.*;  
  255. class Student implements Comparable<Student>  
  256. {  
  257.      private String name;  
  258.      private int ma,ch,en  
  259.      private int sum;  
  260.      Student(String name,int ma,int ch,int en)  
  261.      {  
  262.           this.name = name;  
  263.           this.ma = ma;  
  264.           this.ch = ch;  
  265.           this.en = en;  
  266.           sum = ma+ch+en;  
  267.      }  
  268.      public int getSum()  
  269.      {  
  270.           return sum;  
  271.      }  
  272.      public boolean equals(Student s)  
  273.      {  
  274.           if(!(s instanceof Student))  
  275.                throw new ClassCastException("类型不匹配");  
  276.           return this.name.equals(s.name) && this.sum == s.sum;  
  277.      }  
  278.      public int hashCode()  
  279.      {  
  280.           return this.name.hashCode()+sum*5;  
  281.      }  
  282.      public int compareTo(Student s)  
  283.      {  
  284.           int num = new Integer(this.sum).compareTo(new Integer(s.sum));  
  285.           if(num==0)  
  286.                return this.name.compareTo(s.name);  
  287.           return num;  
  288.      }  
  289.      public String toString()  
  290.      {  
  291.           return "Student["+name+","+ma+","+ch+","+en+"]";  
  292.      }  
  293. }  
  294. class StudentTools  
  295. {  
  296.      public static TreeSet<Student> readInfo() throws IOException  
  297.      {  
  298.           TreeSet<Student> ts = new TreeSet<Student>();  
  299.           BufferedReader br =  
  300.                new BufferedReader(new InputStreamReader(System.in));  
  301.           String line = null;  
  302.           while ((line=br.readLine())!=null)  
  303.           {  
  304.                if("over".equals(line))  
  305.                     break;  
  306.                String[] str = line.split(",");  
  307.                Student s = new Student(str[0],Integer.parseInt(str[1]),  
  308.                                                        Integer.parseInt(str[2]),  
  309.                                                        Integer.parseInt(str[3]));  
  310.                ts.add(s);  
  311.           }  
  312.           br.close();  
  313.           return ts;  
  314.      }  
  315.      public static void writeInfo(TreeSet<Student> ts) throws IOException  
  316.      {  
  317.           BufferedWriter bw = new BufferedWriter(new FileWriter("stu.txt"));  
  318.           for (Student s : ts )  
  319.           {  
  320.                bw.write("学生信息:"+s.toString());  
  321.                bw.write("总分:"+s.getSum());  
  322.                bw.newLine();  
  323.                bw.flush();  
  324.           }  
  325.           bw.close();  
  326.      }  
  327. }  
  328.   
  329. class  StudentInfoTest  
  330. {  
  331.      public static void main(String[] args)  throws IOException  
  332.      {  
  333.           TreeSet<Student> ts = StudentTools.readInfo();  
  334.           StudentTools.writeInfo(ts);  
  335.      }  
  336. }</pre><br>  
  337. <br>  
  338. <p></p>  
  339. <br>  
  340. </div>  
  341. <p></p>  
  342. <pre></pre>  




------ ASP.Net+Android+IO开发.Net培训期待与您交流! ------

原创粉丝点击