Java基础之IO流知识点总结三

File类:
  该类的出现是对文件系统中的文件以及文件夹进行对象的封装。可以通过对象的思想来操作文件以及文件夹。
 
1.  构造函数:
      File(String filename):将一个字符串路径(相对或者绝对)封装成File对象,该路径是可以存在的,也是可以不存在的。
      File(Stringparent,String child);
      File(Fileparent,String child);
2.  特别的字段:separator:跨平台的目录分隔符
     eg.File file = newFile(“C:”+File.separator+”abc”+File.separator+”a.txt”);
 
3.  常见方法     1)  创建:
            boolean createNewFile() throwsIOException:创建文件,如果被创建的文件已经被创建,则不再创建。
            boolean mkdir():创建文件夹。
            boolean mkdirs():创建多级文件夹。
    2)  删除:
           boolean delete():可用于删除文件或者文件夹。
           注意:对于文件夹只能删除不带内容的空文件夹;则对于带内容的文件夹,不可以直接删除,必须要从里往外依次删除。
           void deleteOnExit():删除动作将在系统完成时触发。无论是否发生异常,系统在退出时执行删除动作。
    3)  判断:
           boolean canExecute():该文件是否能执行。
           boolean canWrite():是否是可写文件
           boolean canRead():是否是可读文件
 
           boolean exists():判断文件或者文件夹是否存在。
           boolean isFile():判断File对象中封装的是否是文件。
           boolean isDirectory():判断File对象中封装的是文件夹。
           boolean isHidden():判断文件或者文件夹是否隐藏,在获取硬盘文件或者文件夹时,对于系统目录中的文件,java是无法访 问的。所以遍历,可以避免遍历隐藏文件。
    4)  获取:
           String getName():获取文件或者文件夹的名称。
           String getPath():File对象中封装的路径是什么,获取的就是什么。
           String getAbsolutePath():无论File对象中封装的路径是什么,获取的都是绝对路径。
           String getAbsoluteFile():也返回绝对路径,但是把绝对路径封装成了对象。
           getParent():获取File对象封装文件或者文件夹的父目录。
            注意:如果封装的相对路径,那么返回的是null;
           long length():获取文件大小。
           long lastModified():获取文件或者文件最后一次修改的时间
           static File[] listRoots():获取的是被系统所用的有效盘符。
           string[] list():获取指定目录下当前的文件以及文件夹名称。
           string[] list(Filenamefilter): 可以根据指定的过滤器,过滤后的文件及文件夹名称。
           File[] listFiles():获取指定目录下的文件以及文件夹对象。
5)  重命名:
           renameTo(File):
                File f1 = newFile("c:\\a.txt");
                File f2 = newFile("c:\\b.txt");
                f1.renameTo(f2);//将c盘下的a.txt文件改名为b.txt文件。
例子1:File类的基本方法的使用。

  
  
[java] view plain copy
  1. package cn.itheima.day04;  
  2. /** 
  3.  * File类的常见方法: 
  4.  *    1.创建 
  5.  *       boolean createNewFile() throws IOException 
  6.  *       特点:创建文件,如果被创建的文件已经被创建,则 
  7.  *            不再被创建。和输出流对象不一样,输出流对象 
  8.  *            一建立创建文件,而且文件已经存在回覆盖。 
  9.  *       boolean mkdir():创建文件夹。 
  10.          boolean mkdirs():创建多级文件夹。 
  11.  
  12.  *    2.删除 
  13.  *       boolean delete():可用于删除文件或者文件将夹。 
  14.  *                        如果文件中有内容,是直接删除删除不掉的。 
  15.  *                        删除失败返回false 
  16.  *       void deleteOnExit():删除动作将在系统完成时触发。 
  17.  *                           无论是否发生异常,系统在退出时执行删除动作。 
  18.  *    3.判断 
  19.  *       boolean exists():文件是否存在。 
  20.  *       boolean isFile():判断File对象中封装的是否是文件。 
  21.          boolean isDirectory():判断File对象中封装的是文件夹。 
  22.          boolean isHidden():判断文件或者文件夹是否隐藏,在获取硬盘文件或者文件夹时,对于系统目录中的文件,java是无法访问的。所以遍历,可以避免遍历隐藏文件。 
  23.  *       String getName():获取文件或者文件夹的名称。 
  24.          String getPath():File对象中封装的路径是什么,获取的就是什么。 
  25.          String getAbsolutePath():无论File对象中封装的路径是什么,获取的都是绝对路径。 
  26.          String getAbsoluteFile():也返回绝对路径,但是把绝对路径封装成了对象。 
  27.          getParent():获取File对象封装文件或者文件夹的父目录。 
  28.          注意:如果封装的相对路径,那么返回的是null; 
  29.          long length():获取文件大小。 
  30.          long lastModified():获取文件或者文件最后一次修改的时间 
  31.          static File[] listRoots():获取的是被系统所用的有效盘符。 
  32.          string[] list():获取指定目录下当前的文件以及文件夹名称。 
  33.          string[] list(Filenamefilter): 可以根据指定的过滤器,过滤后的文件及文件夹名称。 
  34.          File[] listFiles():获取指定目录下的文件以及文件夹对象。 
  35.     重命名: 
  36.          renameTo(File): 
  37.             File f1 = new File("c:\\a.txt"); 
  38.             File f2 = new File("c:\\b.txt"); 
  39.             f1.renameTo(f2);//将c盘下的a.txt文件改名为b.txt文件。 
  40.          */  
  41. import java.io.File;  
  42. import java.io.IOException;  
  43. public class FileDemo {  
  44.     public static void main(String[] args) throws IOException {  
  45.         consMethod();  
  46.         //method_1();  
  47.         //method_2();  
  48.         //method_3();  
  49.         method_5();  
  50.     }  
  51.     public static void method_5(){  
  52.         File f1 = new File("F:\\Javajichu\\JavaLianXi\\src\\cn\\itheima\\day04\\file.txt");  
  53.         File f2 = new File("F:\\Javajichu\\JavaLianXi\\src\\cn\\itheima\\day04\\file_copy.txt");  
  54.         sop("rename"+f1.renameTo(f2));  
  55.     }  
  56.     public static void method_3(){  
  57.         File f1 = new File("a.txt");  
  58.         sop("path:"+f1.getPath());  
  59.         sop("AbsolutePath:"+f1.getAbsolutePath());  
  60.         //该方法返回的是绝对路径下的付目录,如果获取相对路径,返回null  
  61.         //如果相对路径中有上一层目录,那么该目录就是返回结果。  
  62.         sop("parent:"+f1.getParent());     
  63.     }     
  64.     public static void method_2(){  
  65.         File file = new File("F:\\Javajichu\\JavaLianXi\\src\\cn\\itheima\\day04\\file.txt");  
  66.         sop("execute:"+file.canExecute());  
  67.         sop("exists:"+file.exists());  
  68.         File dir = new File("F:\\Javajichu\\JavaLianXi\\src\\cn\\itheima\\day04\\wang\\abc\\dd");  
  69.         //System.out.println("mkdir:"+dir.mkdir());  //返回最多一级文件夹  
  70.         sop("mkdirs:"+dir.mkdirs());   //返回多级文件夹  
  71.         //注意:对一个文件对象或者文件夹判断是它是文件还是文件夹时,此时,  
  72.         //文件必须是存在的,通过exists()方法判断。  
  73.         sop("file:"+file.isFile());   //判断是否为文件  
  74.         sop("dir:"+dir.isDirectory());   //判断是否为文件夹  
  75.         sop("absolute:"+file.isAbsolute());   //判断是否为绝对路径  
  76.     }  
  77.     public static void method_1() throws IOException{  
  78.         File file = new File("F:\\Javajichu\\JavaLianXi\\src\\cn\\itheima\\day04\\file.txt");  
  79.         File deletefile = new File("F:\\Javajichu\\JavaLianXi\\src\\cn\\itheima\\day04\\deletefile.txt");  
  80.         sop("create:"+file.createNewFile());  
  81.         sop("delete:"+deletefile.delete());  
  82.     }  
  83.     //创建File对象  
  84.     public static void consMethod(){  
  85.         //将a.txt封装成file对象,可以将已有的和未出现的文件及文件夹封装成对象  
  86.         File f1 = new File("a.txt");  
  87.         //第二种方式(想操作的目录下的文件时可以变化的)  
  88.         File f2 = new File("F:\\Javajichu\\JavaLianXi\\src\\cn\\itheima\\day04","b.txt");  
  89.         //第三种方式  
  90.         File d = new File("F:\\Javajichu\\JavaLianXi\\src\\cn\\itheima\\day04");  
  91.         File f3 = new File(d,"c.txt");  
  92.         //separator跨平台的分隔符  
  93.         File f4= new File("F:"+File.separator+"Javajichu"+File.separator+"JavaLianXi"                       +File.separator+"src"+File.separator+"cn"+File.separator+"itheima"  
  94.                                +File.separator+"day04"+File.separator+"e.txt");         sop("f1="+f1);  
  95.         sop("f2="+f2);  
  96.         sop("f3="+f3);  
  97.         sop("f4="+f4);  
  98.     }  
  99.     public static void sop(Object obj){  
  100.         System.out.println(obj);  
  101.     }  
  102. }  
递归:
其实就是在使用一个功能过程中,又对该功能有需求。就出现了函数自身调用自身。
注意:
     1,一定要限定条件,否则内存溢出。
     2,使用递归时,调用次数不要过多,否则也会出现内存溢出。
例子2:想要列出指定目录下的文件以及文件夹中的文件(子文件)。

  
  
[java] view plain copy
  1. package cn.itheima.day04;  
  2. import java.io.File;  
  3. /** 
  4.  * 列出指定文件目录下的文件或者文件夹,包含子目录的内容, 
  5.  * 也就是列出该文件下的所有内容 
  6.  *  
  7.  * 因为目录中还有目录,只要使用同一个列出目录功能的函数完成即可。 
  8.  * 在列出的目录过程中列出的还是目录,还可以再次调用本功能,也就是 
  9.  * ,函数自身调用自身,则我们称这种方式为递归。 
  10.  *  
  11.  * 递归要限定的条件是: 
  12.  *    1.要有限定条件。 
  13.  *    2.使用递归时,调用次数不要过多,否则也会出现内存溢出。 
  14.  * @author wl-pc 
  15.  */  
  16. public class FileDemo3 {  
  17.     public static void main(String[] args) {  
  18.         File dir = new File("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\");  
  19.         showDir(dir,2);  
  20.         //toBin(6);  
  21.         //int n = getSum(10);  
  22.         //sop("n="+n);  
  23.     }  
  24.     public static String getLevel(int level){  
  25.         StringBuilder sb = new StringBuilder();  
  26.         sb.append("|--");  
  27.         for(int x = 0;x<level; x++){  
  28.             //sb.append("|--");  
  29.             sb.insert(0"|  ");  
  30.               
  31.         }  
  32.         return sb.toString();  
  33.     }  
  34.     //循环的列出文件夹中的文件,若文件夹中还有文件,则调用递归继续循环  
  35.     public static void showDir(File dir,int level){  
  36.         sop(getLevel(level)+dir.getName());  
  37.         level++;  
  38.         File[] files = dir.listFiles();  
  39.         for (int x = 0;x<files.length; x++) {  //判断files是否为文件夹还是文件  
  40.             if(files[x].isDirectory()){  //若files是文件夹,则应该接着进行列表显示  
  41.                 showDir(files[x],level);  
  42.             }else{  
  43.                 sop(getLevel(level)+files[x]);  
  44.             }  
  45.         }  
  46.     }  
  47.     //求6的二进制数  
  48.     public static void toBin(int num){  
  49.         if(num>0){   //递归调用  
  50.             toBin(num/2);  
  51.             sop(num%2);   //没次都先被执行  
  52.             //num = num/2;  
  53.         }  
  54.     }  
  55.     //求和  
  56.     public static int getSum(int n){  
  57.         if(n==1)  
  58.             return 1;  
  59.         return n+getSum(n-1);  
  60.     }   
  61.     public static void sop(Object obj){  
  62.         System.out.println(obj);  
  63.     }  
  64. }  
例子3:删除一个带内容的目录。

  
  
[java] view plain copy
  1. package cn.itheima.day04;  
  2. import java.io.File;  
  3. /** 
  4.  * 删除一个带内容的目录。  
  5.  * 删除原理: 在windows删除目录是从里面往外.既然 
  6.  *            从里往外删除,就需要用到了递归。 
  7. * @author wl-pc 
  8.  */  
  9. public class RemoveDir {  
  10.     public static void main(String[] args) {  
  11.         File file = new File("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\aa");  
  12.         removeDir(file);  
  13.     }  
  14.     //删除文件夹  
  15.     public static void removeDir(File dir) {  
  16.         File[] files = dir.listFiles();  
  17.         for (int x = 0; x < files.length; x++) {  
  18.              if(files[x].isDirectory())  
  19.                  removeDir(files[x]);  
  20.              else   
  21.                  System.out.println(files[x].toString()+":file:"+files[x].delete());  
  22.         }  
  23.         System.out.println(dir.toString()+":dir:"+dir.delete());  
  24.     }  
  25. }  
例子4:将一个指定目录下所有的java文件的绝对路径,存储到一个文本文件中,建立一个java文件的列表文件。

  
  
[java] view plain copy
  1. package cn.itheima.day04;  
  2. import java.io.BufferedWriter;  
  3. import java.io.File;  
  4. import java.io.FileWriter;  
  5. import java.io.IOException;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8. /** 
  9.  * 练习: 
  10.  *    将一个指定目录下所有的java文件的绝对路径,存储到一个文本文件中。 
  11.  *     建立一个java文件的列表文件。 
  12.  * 思路: 
  13.  *    1.对指定的目录进行递归。 
  14.  *    2.获取在递归过程中所有java文件的路径。 
  15.  *    3.将这些路径存储到集合中。 
  16.  *    4.将集合中的数据写入到一个文件中。    
  17.  * @author wl-pc 
  18.  */  
  19. public class JavaFileList {  
  20.     public static void main(String[] args) throws IOException {  
  21.         File dir = new File("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\");  
  22.         List<File> list = new ArrayList<File>();  
  23.         fileToList(dir,list);  
  24.         System.out.println(list.size());  
  25.         File file = new File("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\","javaList.txt");  
  26.         writeToFile(list,file.toString());  
  27.     }  
  28.     public static void fileToList(File dir,List<File> list){  
  29.         File[] files = dir.listFiles();  
  30.         for (File file : files) {  
  31.             if(file.isDirectory()){  //遍历目录,如果是目录则继续遍历。  
  32.                 fileToList(file, list);  //调用递归方法  
  33.             }else{  
  34.                 if(file.getName().endsWith(".java")){  //将得到的java文件存储到集合中  
  35.                     list.add(file);  
  36.                 }  
  37.             }  
  38.         }  
  39.     }  
  40.     //数据持久化  
  41.     public static void writeToFile(List<File> list,String javaListFile) throws IOException{  
  42.         BufferedWriter bufw=null;  
  43.         //javaListFile = "F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\";  
  44.         try {  
  45.             bufw = new BufferedWriter(new FileWriter(javaListFile));  
  46.             for (File f : list) {  
  47.                 String path = f.getAbsolutePath();  //获取绝对路径  
  48.                 bufw.write(path);  
  49.                 bufw.newLine();  
  50.                 bufw.flush();  
  51.             }  
  52.         } catch (IOException e) {  
  53.             throw e;  
  54.         }finally{  
  55.             try {  
  56.                 if(bufw!=null){  
  57.                    bufw.close();  
  58.                 }  
  59.             } catch (IOException e) {  
  60.                 throw e;  
  61.             }  
  62.         }  
  63.     }  
  64. }  
例子5:利用Perperties类得到它里面存储的数据信息的值。

  
  
[java] view plain copy
  1. package cn.itheima.day04;  
  2. import java.util.Properties;  
  3. import java.util.Set;  
  4. /** 
  5.  * Perperties是hashtable的子类,也就是说它具备了map集合的特点,而且 
  6.  * 它里面存储的都是字符串,不需要泛型。 
  7.  * 是集合中和IO技术相结合的集合容器。 
  8.  * 该对象的特点可以用于键值对形式的配置文件。 
  9.  * @author wl-pc 
  10. */  
  11. public class PropertiesDemo {  
  12.   
  13.     public static void main(String[] args) {  
  14.           
  15.         setAndGet();  
  16.     }  
  17.     //设置和回去元素  
  18.     public static void setAndGet(){  
  19.         Properties properties = new Properties();  
  20.         properties.setProperty("zhangsan""30");  //设置属性,按键值对形式设置。  
  21.         properties.setProperty("lisi""39");  
  22.         //System.out.println(properties);  
  23.         String value = properties.getProperty("lisi");  
  24.         //System.out.println(value);  
  25.         properties.setProperty("lisi""89");  
  26.         Set<String> values = properties.stringPropertyNames();  
  27.         for (String s : values) {  
  28.             System.out.println(s+"::"+properties.getProperty(s));  
  29.         }  
  30.     }  
  31. }  
例子6:利用Properties类读取文件中的数据(数据格式为:键=值)存储到集合中,并读取到控制台上,并且可以修改文件中的数据。

  
  
[java] view plain copy
  1. package cn.itheima.day04;  
  2. import java.io.BufferedReader;  
  3. import java.io.FileInputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.FileReader;  
  7. import java.io.IOException;  
  8. import java.util.Properties;  
  9. import java.util.Set;  
  10. /** 
  11.  * Perperties是hashtable的子类,也就是说它具备了map集合的特点,而且 
  12.  * 它里面存储的都是字符串,不需要泛型。 
  13.  * 是集合中和IO技术相结合的集合容器。 
  14.  * 该对象的特点可以用于键值对形式的配置文件。 
  15.  * 在加载数据时需要数据要有固定的格式,通常是:键=值 
  16.  * @author wl-pc 
  17. */  
  18. public class PropertiesDemo {  
  19.     public static void main(String[] args) throws IOException {  
  20.         //setAndGet();  
  21.         //method_1();  
  22.         loadDemo();  
  23.     }  
  24.     public static void loadDemo(){  
  25.         FileInputStream fis=null;  
  26.         FileOutputStream fos=null;  
  27.         try {  
  28.             Properties properties = new Properties();  
  29.             fis = new FileInputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\info.txt");  
  30.             properties.load(fis);  //将流中的数据加载到集合中   
  31.             //System.out.println(properties);  
  32.             //properties.list(System.out);  //列出集合目录  
  33.             properties.setProperty("wangwu""99");  //改变内存中的数据的值,不改变文件中的值  
  34.             fos = new FileOutputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\info.txt");  
  35.             properties.store(fos, "haha");   //将内存中的结果存储到一个流中,并且存储到一个文件中。  
  36.             System.out.println(properties);  
  37.         } catch (FileNotFoundException e) {  
  38.             System.out.println(e.toString());  
  39.         } catch (IOException e) {  
  40.             System.out.println(e.toString());  
  41.         }finally{  
  42.             if(fis!=null){  
  43.                 try {  
  44.                     fis.close();  
  45.                 } catch (IOException e) {  
  46.                     System.out.println(e.toString());  
  47.                 }  
  48.             }  
  49.             if(fos!=null){  
  50.                 try {  
  51.                     fos.close();  
  52.                 } catch (IOException e) {  
  53.                     System.out.println(e.toString());  
  54.                 }  
  55.             }  
  56.         }  
  57.     }  
  58.     //演示:如何将流中的数据存储到集合中  
  59.     //想要将Info.xt中的键值数据存储到集合中的操作  
  60.     /** 
  61.      * 思路: 
  62.      *    1.用一个流和info.txt文件关联。 
  63.      *    2.读取一行数据,将该行数据用等号进行切割。 
  64.      *    3.等号左边作为键,右边作为值,存入到Properties中即可。 
  65.      * @throws IOException       
  66.      */  
  67.     public static void method_1() throws IOException{  
  68.         BufferedReader bufr=null;  
  69.         try {  
  70.             bufr = new BufferedReader(new FileReader("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\info.txt"));  
  71.             String line = null;  
  72.             Properties properties = new Properties();  
  73.             while((line = bufr.readLine())!=null){  
  74.                 String[] arr = line.split("=");  
  75.                 System.out.println(arr[0]+"----"+arr[1]);  
  76.                 properties.setProperty(arr[0], arr[1]);  
  77.             }  
  78.             System.out.println(properties);  
  79.         } catch (FileNotFoundException e) {  
  80.             // TODO Auto-generated catch block  
  81.             e.printStackTrace();  
  82.         }finally{  
  83.             if(bufr!=null){  
  84.                 bufr.close();  
  85.             }  
  86.         }  
  87.     }  
  88.     //设置和回去元素  
  89.     public static void setAndGet(){  
  90.         Properties properties = new Properties();  
  91.         properties.setProperty("zhangsan""30");  //设置属性,按键值对形式设置。  
  92.         properties.setProperty("lisi""39");  
  93.         //System.out.println(properties);  
  94.         String value = properties.getProperty("lisi");  
  95.         //System.out.println(value);  
  96.         properties.setProperty("lisi""89");  
  97.         Set<String> values = properties.stringPropertyNames();  
  98.         for (String s : values) {  
  99.             System.out.println(s+"::"+properties.getProperty(s));  
  100.         }  
  101.     }  
  102. }  

例子7:用于记录应用程序运行的次数,如果使用次数已到,那么给出注册提示。

 
 
[java] view plain copy
  1. package cn.itheima.day04;  
  2. <pre>import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.util.Properties;  
  7. /** 
  8.  * 用于记录应用程序运行的次数。 
  9.  * 如果使用次数已到,那么给出注册提示。 
  10.  * 很容易想到使用计数器。 
  11.  * 可是,该计数器定义在程序中,随着程序的运行而在内存中存在,并且进行自增, 
  12.  * 可是,随着该应用程序的退出,该计数器也在内存中消失了。 
  13.  * 下一次,在程序启动时,又重新开始从0记数了 
  14.  * 这样不是我们想要的。 
  15.  *  
  16.  * 程序即使结束,该计数器的值也存在。 
  17.  * 下次程序启动时也会先加载该计数器的值,并且技术加1后在重新存储起来, 
  18.  *  
  19.  * 所以要建立一个配置文件,用于记录该软件的使用次数。 
  20.  * 该配置文件使用键值对的形式,这样便于阅读数据,操作数据。 
  21.  * 键值对数据,是一个map集合。 
  22.  * 数据是以文件的形式存储的,所以要使用io技术。 
  23.  * 那么,map+io----->properties. 
  24. * 配置文件可以实现应用程序的数据的共享。  
  25.  * @author wl-pc 
  26. */  
  27. public class RunCount {  
  28.     public static void main(String[] args) throws IOException {  
  29.         Properties properties = new Properties();  
  30.         FileInputStream fis=null;  
  31.         File file = new File("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\count.txt");  
  32.             if(!file.exists())  
  33.                 file.createNewFile();  
  34.             else  
  35.                 fis = new FileInputStream(file);  
  36.             properties.load(fis);  
  37.             int count = 0;  
  38.             String value = properties.getProperty("time");  
  39.             if(value!=null){  
  40.                 count = Integer.parseInt(value);  
  41.                 if(count>=5){  
  42.                     System.out.println("你好,你使用的次数已到,请注册后,使用。");  
  43.                 }  
  44.             }  
  45.             count++;  
  46.             properties.setProperty("time", count+"");  
  47.             FileOutputStream fos = new FileOutputStream(file);  
  48.             properties.store(fos, "hello");  
  49.             fos.close();  
  50.             fis.close();  
  51.     }  
[java] view plain copy
  1. }  
 

IO包中常见的对象:
     字节流:
          FileInputStream
          FileOutputStream
          BufferedInputStream
          BufferedOutputStream
     字符流:
          FilerReader
          FileWriter
          BufferedReader
          BufferedWriter
     转换流:
          InputStreamReader
          OutputStreamWriter
文件对象:
      File
    打印流:
         PrintStream
         PrintWriter
注意:所有的带File的流对象都可以直接操作File对象。
IO包中的其他对象:
     1.打印流
PrintStream:是一个字节打印流,System.out对应的类型就是PrintStream.
它的构造函数可以接收三种数据类型。
     1.  字符串路径。
     2.  File对象
     3.  OutputStream
PrintWriter:是一个字符打印流,构造函数可以接收四种类型的值。
     1.  字符串路径。
     2.  File对象。
对于1.2类型的数据,还可以指定编码表。也就是字符集。
      3.  OutputStream
      4.  Writer
对于3.4类型的数据,可以指定自动刷新。
注意:该自动刷新的值为true时,只有三个方法可用:println,printf,format.
//如果想要既有自动刷新,又可执行编码。如何完成流对象的包装呢?
PrintWriter pw = new PrintWriter(newOutputStreamWriter(new FileOutputStream(“a.txt”)));
//如果想要提高效率,还要使用打印方法。
PrintWrterpw = newPrintWriter(new BufferdWriter(new OutputSteamWriter(new FileOutputStream("a.txt"),"utf-8")),true);

例子8:用打印流对象,用打印流接收用户在控制台输入的数据,然后用打印流输出到控制台上或者一个文件中

 
 
[java] view plain copy
  1. package cn.itheima.day04;  
  2. import java.io.BufferedReader;  
  3. import java.io.BufferedWriter;  
  4. import java.io.FileWriter;  
  5. import java.io.IOException;  
  6. import java.io.InputStreamReader;  
  7. import java.io.PrintWriter;  
  8. public class PrintStreamDemo {  
  9.     public static void main(String[] args) throws IOException {  
  10.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
  11.         //PrintWriter out = new PrintWriter(System.out,true);  
  12.         PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\a.txt")),true);  
  13.         String line=null;  
  14.         while((line=br.readLine())!=null){  
  15.             if("over".equals(line)){  
  16.                 break;  
  17.             }  
  18.             out.println(line.toUpperCase());  
  19.             //out.flush();  
  20.         }  
  21.         out.close();  
  22.         br.close();  
  23.     }  
  24. }  

2.序列流,也成合并流。
SequenceInputStream:
       特点:可以将多个读取流合并成一个流,这样操作起来很方便。
       原理:其实就是将每一个读取流对象存储到一个集合中,最后一个流对象结尾作为这个流的结尾。
两个构造函数      1.  SequenceInputStream(InputStreamin1,InputStream in2):可以将两个读取流合并成一个流。
      2.  SequenceInputStream(Enumeration<?Extents InputStream> en):可以将枚举中的多个流合并成一个流。
例子9:将3个读取流文件合并成一个读取流文件。

 
 
[java] view plain copy
  1. package cn.itheima.day04;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.SequenceInputStream;  
  6. import java.util.Enumeration;  
  7. import java.util.Vector;  
  8. public class SequenceDemo {  
  9.   
  10.     public static void main(String[] args) throws IOException {  
  11.         Vector<FileInputStream> v = new Vector<FileInputStream>();  
  12.         v.add(new FileInputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\1.txt"));  
  13.         v.add(new FileInputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\2.txt"));  
  14.         v.add(new FileInputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\3.txt"));  
  15.         Enumeration<FileInputStream> en = v.elements();   //枚举类型(将多个读取流合并成一个读取流)  
  16.         SequenceInputStream sis = new SequenceInputStream(en);     
  17.         FileOutputStream fos = new FileOutputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\4.txt");  
  18.         byte[] buf = new byte[1024];  
  19.         int len = 0;  
  20.         while((len=sis.read(buf))!=-1){  
  21.             fos.write(buf,0,len);  
  22.         }  
  23.         fos.close();  
  24.         sis.close();  
  25.     }  
  26. }  
作用:可以用于多个数据的合并。
注意:因为Enumeration是Vector中特有的取出方式。而Vector被ArrayList取代。所以要使用ArrayList集合效率更高一些。
那么如何获取Enumeration呢?

 
 
[java] view plain copy
  1. ArrayList<FileInputStream > al = new ArrayList<FileInputStream>();  
  2. for(int x=1; x<4; x++)  
  3.      al.add(new FileInputStream(x+".txt"));  
  4.      Iterator<FileInputStream> it = al.iterator();  
  5.      Enumeration<FileInputStream> en = new Enumeration<FileInputStream>(){  
  6.      public boolean hasMoreElements(){  
  7.          return it.hasNext();  
  8.      }  
  9.      public FileInputStream nextElement(){  
  10.          return it.next();  
  11.      }  
  12. };  
  13. //多个流就变成了一个流,这就是数据源。  
  14. SequenceInputStream sis = new SequenceInputStream(en);  
  15. //创建数据目的。  
  16. FileOutputStream fos = new FileOutputStream("4.txt");  
  17. byte[] buf = new byte[1024*4];  
  18. int len = 0;  
  19. while((len=sis.read(buf))!=-1){  
  20.     fos.write(buf,0,len);  
  21. }  
  22. fos.close();  
  23. sis.close();  
例子10.文件的切割和合并。

 
 
[java] view plain copy
  1. package cn.itheima.day04;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.SequenceInputStream;  
  7. import java.util.ArrayList;  
  8. import java.util.Enumeration;  
  9. public class SplitFile {  
  10.     public static void main(String[] args) throws IOException {  
  11.         //splitFile();  
  12.         merge();  
  13.     }  
  14.     //合并文件  
  15.     public static void merge() throws IOException{  
  16.         ArrayList<FileInputStream> aList = new ArrayList<FileInputStream>();  
  17.         for(int x = 1;x<=4;x++){  
  18.             aList.add(new FileInputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\pic\\"+x+".part"));  
  19.         }  
  20.         final java.util.Iterator<FileInputStream> it = aList.iterator();  
  21.         Enumeration<FileInputStream> en = new Enumeration<FileInputStream>() {  
  22.             public boolean hasMoreElements() {  
  23.                 return it.hasNext();  
  24.             }  
  25.             public FileInputStream nextElement() {  
  26.                 return it.next();  
  27.             }  
  28.         };  
  29.         SequenceInputStream sis = new SequenceInputStream(en);  
  30.         FileOutputStream fos = new FileOutputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\pic\\0.png");  
  31.         byte[] buf = new byte[1024];  
  32.         int len=0;  
  33.         while((len=sis.read(buf))!=-1){  
  34.             fos.write(buf,0,len);  
  35.         }  
  36.         fos.close();  
  37.         sis.close();  
  38.     }  
  39.     //切割文件  
  40.     public static void splitFile() throws IOException{  
  41.         FileInputStream fis = new FileInputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\1.png");  
  42.         FileOutputStream fos = null;  
  43.         byte[] buf = new byte[1024*1024];  
  44.         int len =0;  
  45.         int count =1;  
  46.         while((len=fis.read(buf))!=-1){  
  47.             fos = new FileOutputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day04\\pic\\"+(count++)+".part");  
  48.             fos.write(buf,0,len);  
  49.             fos.close();  
  50.         }  
  51.         if(fos!=null){  
  52.             fos.close();  
  53.         }  
  54.         fis.close();  
  55.     }  
  56. }  
操作对象的流:
     ObjectInputStream
     ObjectOutputStream 
可以通过这两个流对象直接操作已有的对象,并将对象进行本地持久化存储。存储后的对象可以进行网络传输。
两个对象的特有方法:
       ObjectInputStream
       Object readObject():该方法抛出异常:ClassNotFountException
       ObjectOutputStream
       void writeObject(Object):被写入的对象必须实现一个接口:Serializable,否则会抛出异常:NotSerializableException
Serializable:该接口其实就是一个没有方法的标记接口。
用于给类指定一个UID。该UID是通过类中的可序列化成员的数字签名运出来的一个long型的值。只要是这些成员没有变化,那么该值每次运算都一样。该值用于判断被序列化的对象和类文件是否兼容。如果被序列化的对象需要被不同的类版本所兼容。可以在类中自定义UID。
定义方式:static final long serialVersionUID = 42L;
注意:对应静态的成员变量,不会被序列化。
对应非静态也不想被序列化的成员而言,可以通过transient关键字修饰。
例子11.利用ObjectInputStream和ObjectOutputStream,写入和读取文件中的数据

 
 
[java] view plain copy
  1. package cn.itheima.day05;  
  2. import java.io.Serializable;  
  3. public class Person implements Serializable{  
  4.     private static final long serialVersionUID = 42L;  //固定标示  
  5.     private String name;  
  6.     transient int age;   //对非静态的属性不想序列化的话,可以加一个关键字transient  
  7.     static String country="cn";  //静态不能被序列化  
  8.     public Person() {  
  9.         super();  
  10.     }  
  11.     public Person(String name, int age,String country) {  
  12.         super();  
  13.         this.name = name;  
  14.         this.age = age;  
  15.         this.country=country;  
  16.     }  
  17.     public static String getCountry() {  
  18.         return country;  
  19.     }  
  20.     public static void setCountry(String country) {  
  21.         Person.country = country;  
  22.     }  
  23.     public String getName() {  
  24.         return name;  
  25.     }  
  26.     public void setName(String name) {  
  27.         this.name = name;  
  28.     }  
  29.     public int getAge() {  
  30.         return age;  
  31.     }  
  32.     public void setAge(int age) {  
  33.         this.age = age;  
  34.     }  
  35.     @Override  
  36.     public String toString() {  
  37.         return "Person [name=" + name + ", age=" + age + ",country=" + country + "]";  
  38.     }  
  39. }  
  40.   
  41.   
  42. package cn.itheima.day05;  
  43. import java.io.FileInputStream;  
  44. import java.io.FileOutputStream;  
  45. import java.io.IOException;  
  46. import java.io.ObjectInputStream;  
  47. import java.io.ObjectOutputStream;  
  48. public class ObjectStreamDemo {  
  49.     public static void main(String[] args) throws IOException, ClassNotFoundException {  
  50.         //writeObj();  
  51.         readObj();  
  52.     }  
  53.     //读文件中的持久化类  
  54.     public static void readObj() throws  IOException, ClassNotFoundException{  
  55.         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\obj.txt"));  
  56.         Person person = (Person)ois.readObject();  
  57.         System.out.println(person);  
  58.         ois.close();  
  59.     }  
  60.     //把类变成持久化  
  61.     public static void writeObj() throws  IOException{  
  62.         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\obj.txt"));  
  63.         oos.writeObject(new Person("lisi0",39,"china"));  
  64.         oos.close();  
  65.     }  
  66. }  
管道流:
   PipedInputStream
   PipedOutputStream
   特点:
     读取管道流和写入管道流可以进行连接。
     连接的方式:
         1.  通过两个流对象的构造函数。
         2.  通过两个对象的connect方法。
 
     通常两个流在使用时,需要加入多线程技术,也就是让读写同时运行。
     注意:对于read方法。该方法是阻塞式的,也就是没有数据的情况,该方法会等
例子12.管道流的应用,用到多线程的知识。

 
 
[java] view plain copy
  1. package cn.itheima.day05;  
  2. import java.io.IOException;  
  3. import java.io.PipedInputStream;  
  4. import java.io.PipedOutputStream;  
  5. class Read implements Runnable {  
  6.     private PipedInputStream in;  
  7.     Read(PipedInputStream in){  
  8.         this.in = in;  
  9.     }  
  10.     public void run() {  
  11.         try {  
  12.             byte[] buf = new byte[1024];  
  13.             int len = 0;  
  14.             System.out.println("读取前没有数据,阻塞");  
  15.             len = in.read(buf);  
  16.             System.out.println("读取到数据,阻塞结束");  
  17.             String s = new String(buf,0,len);  
  18.             System.out.println(s);  
  19.             in.close();  
  20.         } catch (IOException e) {  
  21.             throw new RuntimeException("管道读取流失败");  
  22.         }  
  23.     }  
  24. }  
  25. class Writer implements Runnable {  
  26.     private PipedOutputStream out;  
  27.     public Writer(PipedOutputStream out) {  
  28.         this.out = out;  
  29.     }  
  30.     public void run() {  
  31.         try {  
  32.             System.out.println("开始写入数据等待6秒后");  
  33.             Thread.sleep(6000);  
  34.             out.write("管道 来啦".getBytes());  
  35.             out.close();  
  36.         } catch (IOException e) {  
  37.             throw new RuntimeException("管道输出流失败");        
  38.         } catch (InterruptedException e) {  
  39.             // TODO Auto-generated catch block  
  40.             e.printStackTrace();  
  41.         }  
  42.     }  
  43. }  
  44. public class PipedStream {  
  45.     public static void main(String[] args) throws IOException {  
  46.         PipedInputStream in = new PipedInputStream();  
  47.         PipedOutputStream out = new PipedOutputStream();  
  48.         in.connect(out);  
  49.         Read r = new Read(in);  
  50.         Writer w= new Writer(out);  
  51.         new Thread(r).start();  
  52.         new Thread(w).start();  
  53.     }  
  54. }  
RandomAccessFile类:
该类特点:该类不算IO体系中的子类,而是直接继承Object,但是它是IO包中的成员,因为它具备读和写功能,因为它内部封装了一个数组,而且通过指针对数组的元素进行操作。可以通过,getFilePointer获取指针位置,同时可以通过seek改变指针的位置。
其实完成读写的原理:内部封装了字节输入流和字节输出流。
通过构造函数,可以看出,该类只能操作文件,有局限性。
     而且操作文件还有模式(4种):r(只读)   rw(可读可写)   rws      rwd
而且该对象的构造函数要操作的文件不存在,会自动的创建,如果存在则不会覆盖。
如果模式是r: 则不会创建文件,会去读取一个已存在的文件,如果该文件不存在,则会出现异常。
如果模式是rw:操作的文件不存在,会自动创建,如果存在则不会原来的数据。
例子13:利用RandomAccessFile的seek()方法实现随机的读写和访问。
[java]  view plain  copy
  1. package cn.itheima.day05;  
  2. import java.io.FileNotFoundException;  
  3. import java.io.IOException;  
  4. import java.io.RandomAccessFile;  
  5. public class RandomAccessFileDemo {  
  6.     public static void main(String[] args) throws IOException {  
  7.         //writeFile();  
  8.         //writerFile_2();  
  9.         readFile();  
  10.         //System.out.println(Integer.toBinaryString(258));  
  11.     }  
  12.       
  13.     public static void readFile() throws IOException{  
  14.         //RandomAccessFile可以随机的读写和访问。  
  15.         RandomAccessFile raf=new  RandomAccessFile("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\ran.txt""r");  
  16.         //raf.write("haha".getBytes());被屏蔽  
  17.         //调整对象中的指针,来在指定的位置读取和写入数据  
  18.         //raf.seek(8*1);  //seek(long pos) 设置到此文件开头测量到的文件指针偏移量,在该位置发生下一个读取或写入操作(seek前后都能跳)  
  19.           
  20.         //跳过指定的字节数((-1,0)缺点:不能往回跳(不能往-1跳),只能往前跳(往0跳))  
  21.         raf.skipBytes(8*3);  
  22.         byte[] buf = new byte[4];  
  23.         raf.read(buf);  
  24.         String name = new String(buf);  
  25.         System.out.println("name="+name);  
  26.         int age = raf.readInt();  
  27.         System.out.println("age="+age);  
  28.         raf.close();  
  29.     }  
  30.     public static void writerFile_2(){  
  31.         try {  
  32.             RandomAccessFile raf = new RandomAccessFile("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\ran.txt""rw");  
  33.             //调整对象中的指针,来在指定的位置读取和写入数据  
  34.             raf.seek(8*3);  
  35.             raf.write("周期".getBytes());  
  36.             raf.writeInt(103);        
  37.             raf.close();  
  38.               
  39.         } catch (FileNotFoundException e) {  
  40.             e.printStackTrace();  
  41.         } catch (IOException e) {  
  42.             e.printStackTrace();  
  43.         }  
  44.     }  
  45.     public static void writeFile(){  
  46.         try {  
  47.             RandomAccessFile raf = new RandomAccessFile("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\ran.txt""rw");  
  48.             raf.write("张三".getBytes());  
  49.             raf.writeInt(97);  
  50.             raf.write("王五".getBytes());  
  51.             raf.writeInt(23);  
  52.             raf.close();  
  53.         } catch (FileNotFoundException e) {  
  54.             e.printStackTrace();  
  55.         } catch (IOException e) {  
  56.             e.printStackTrace();  
  57.         }  
  58.     }  
  59. }  
操作基本数据类型的流对象:DataInputStream.
DataInputStream:
   DatsInputStream(InputStream);
     它操作的基本数据类型的方法:
        Int readInt():一次读取四个字节,并将其转换成int值。
        booleanreadBoolean():一次读取一个字节。
        short readShort():
        longreadLong();
        String readUTF():按照utf-8修改版读取字符。注意,它只能读取writeUTF()写入的字符数据。
DataOutputStream:
     DataOutputStream(OutputStream):
操作基本数据类型的方法:
       writeInt(int):一次写入四个字节。
注意和write(int)不同。write(int)只将该整数的最低一个8位写入。剩余三个8位丢弃。
      writeBoolean(boolean);
      writeShort(short);
      writeLong(long);   
writeUTF(String):按照utf-8修改版将字符数据进行存储。只能通过readUTF读取。通常只要操作基本数据类型的数据。就需要通过DataStram进行包装。通常成对使用。

例子14:利用DataInputStream和DataOutputStream操作基本数据类型进行读写操作。

 
 
[java] view plain copy
  1. package cn.itheima.day05;  
  2. import java.io.DataInputStream;  
  3. import java.io.DataOutputStream;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. /** 
  9.  * 可以用于操作基本数据类型的数据。 
  10.  * @author wl-pc 
  11. */  
  12. public class DataStreamDemo {  
  13.     public static void main(String[] args) {  
  14.         //writeData();  
  15.         //readData();  
  16.         //WriteUtfDemo();  
  17.         readUtfDemo();  
  18.     }  
  19.     //读出utf格式的数据  
  20.     public static void readUtfDemo(){  
  21.         try {  
  22.             DataInputStream dis = new DataInputStream(new FileInputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\utfdata.txt"));  
  23.             String value = dis.readUTF();  
  24.             System.out.println(value);  
  25.             dis.close();  
  26.         } catch (FileNotFoundException e) {  
  27.             e.printStackTrace();  
  28.         } catch (IOException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.     }  
  32.     //写入utf格式的数据  
  33.     public static void WriteUtfDemo(){  
  34.         try {  
  35.             DataOutputStream dos = new DataOutputStream(new FileOutputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\utfdata.txt"));  
  36.             dos.writeUTF("小明");  
  37.             dos.close();  
  38.         } catch (FileNotFoundException e) {  
  39.             e.printStackTrace();  
  40.         } catch (IOException e) {  
  41.             e.printStackTrace();  
  42.         }  
  43.     }  
  44.     //读取数据  
  45.     public static void readData(){  
  46.         try {  
  47.             DataInputStream dis = new DataInputStream(new FileInputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\data.txt"));  
  48.             int num = dis.readInt();  
  49.             boolean b = dis.readBoolean();  
  50.             double d = dis.readDouble();  
  51.             System.out.println("num="+num);  
  52.             System.out.println("b="+b);  
  53.             System.out.println("d="+d);  
  54.             dis.close();  
  55.         } catch (FileNotFoundException e) {  
  56.             e.printStackTrace();  
  57.         } catch (IOException e) {  
  58.             e.printStackTrace();  
  59.         }  
  60.     }  
  61.     //写入数据  
  62.     public static void writeData(){  
  63.         try {  
  64.             DataOutputStream dos = new DataOutputStream(new FileOutputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\data.txt"));  
  65.             dos.writeInt(234);  
  66.             dos.writeBoolean(true);  
  67.             dos.writeDouble(98.03);  
  68.             dos.close();  
  69.         } catch (FileNotFoundException e) {  
  70.             e.printStackTrace();  
  71.         } catch (IOException e) {  
  72.             e.printStackTrace();  
  73.         }  
  74.     }  
  75. }  

操作数组的流对象:
1,操作字节数组
     ByteArrayInputStream:特点:在构造时需要接收数据源,而且数据源是一个字节数组,
     ByteArrayOutputStream 特点:在构造的时候,不用定义数组目的。因为该对象中已经内部封装了一个可变长度的字节数组。
     toByteArray();
     toString();
     writeTo(OutputStream):输入内容到一个文件中。
因为这两个流对象都操作的是数组,并没有使用系统资源,所以,没有不用进行流的关闭。(即使流对象关闭,还是可以使用的。
在流---规律讲解时:
    源设备:
         键盘 System.in     硬盘FileStream    内存ArrayStream
    目的:
         控制台System.out  硬盘FileStream     内存ArrayStream
用流的读写思想去操作数据。
例子15:ByteArrayInputStream和ByteArrayOutputStream来读写数据。

 
 
[java] view plain copy
  1. package cn.itheima.day05;  
  2. import java.io.ByteArrayInputStream;  
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.FileNotFoundException;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. public class ByteArrayStream {  
  8.     public static void main(String[] args) throws FileNotFoundException, IOException {  
  9.         //明确数据源  
  10.         ByteArrayInputStream bis = new ByteArrayInputStream("abcdefg".getBytes());  
  11.         //明确数据目的  
  12.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  13.         System.out.println(bos.size());  
  14.         int by = 0;  
  15.         while ((by = bis.read())!=-1) {  
  16.             bos.write(by);  
  17.         }  
  18.         System.out.println(bos.size());  
  19.         System.out.println(bos.toString());  
  20.         bos.writeTo(new FileOutputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\a.txt"));  
  21.     }  
  22. }  
2,操作字符数组。
     CharArrayReader
     CharArrayWriter
对于这些流,源是内存。目的也是内存。而且这些流并未调用系统资源。使用的就是内存中的数组。
所以这些在使用的时候不需要close。
操作数组的读取流在构造时,必须要明确一个数据源。所以要传入相对应的数组。
对于操作数组的写入流,在构造函数可以使用空参数。因为它内置了一个可变长度数组作为缓冲区。
编码转换:
      在io中涉及到编码转换的流是转换流和打印流。但是打印流只有输出。在转换流中是可以指定编码表的。
      默认情况下,都是本机默认的码表。GBK. 这个编码表怎么来的?System.getProperty("file.encoding");
常见码表:
      ASCII:美国标准信息交换码。使用的是1个字节的7位来表示该表中的字符。
      ISO8859-1:拉丁码表。使用1个字节来表示。
      GB2312:简体中文码表。
      GBK:简体中文码表,比GB2312融入更多的中文文件和符号。
      unicode:国际标准码表。都用两个字节表示一个字符。
      UTF-8:对unicode进行优化,每一个字节都加入了标识头。
编码转换:
    (String--àbyte[])
字符串-->字节数组:编码。
       通过str.getBytes(charset);
    (byte[]--àString)
字节数组-->字符串:解码。
       通过String类的构造函数完成。new String(byte[],charset);
如果编错了,没救!
如果编对了,解错了,有可能还有救!
String s = "你好";
//编码。
byte[] b =s.getBytes("GBK");
//解码。
String s1 = newString(b,"iso8859-1");
System.out.println(s1);
 //想要还原。
/*
对s1先进行一次解码码表的编码。获取原字节数据。
然后在对原字节数据进行指定编码表的解码。
*/
byte[] b1 = s1.getBytes("iso8859-1");
String s2 = newString(b1,"gbk");
System.out.println(s2);//你好。
这种情况在tomcat服务器会出现。因为tomcat服务器默认是iso8859-1的编码表。所以客户端通过浏览器向服务端通过get提交方式提交中文数据时,服务端获取到会使用ISO8859-1进行中文数据的解码。会出现乱码。这时就必须要对获取的数据进行iso8859-1编码。然后在按照页面指定的编码表进行解码即可而对于post提交,这种方法也通用。但是post有更好的解决方式。
request.setCharacterEncoding("utf-8");即可。
所以建立客户端提交使用post提交方式。

例子16:写入和读出UTF-8编码和GBK编码的文件。

[java] view plain copy
  1. package cn.itheima.day05;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileNotFoundException;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStreamReader;  
  7. import java.io.OutputStreamWriter;  
  8. public class EncodeStream {  
  9.     public static void main(String[] args) {  
  10.         //writeText();  
  11.         readText();  
  12.     }  
  13.     public static void readText(){  
  14.         try {  
  15.             InputStreamReader isr = new InputStreamReader(new FileInputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\gbk.txt"),"UTF-8");  
  16.             int len = 0;  
  17.             char[] buf = new char[10];  
  18.             len = isr.read(buf);  
  19.             String str = new String(buf,0,len);  
  20.             System.out.println("str="+str);  
  21.             isr.close();  
  22.         } catch (FileNotFoundException e) {  
  23.             e.printStackTrace();  
  24.         } catch (IOException e) {  
  25.             e.printStackTrace();  
  26.         }  
  27.     }  
  28.     public static void writeText(){  
  29.         try {  
  30.             OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\gbk.txt"),"UTF-8");  
  31.             osw.write("你好");  
  32.             osw.close();  
  33.         } catch (FileNotFoundException e) {  
  34.             e.printStackTrace();  
  35.         } catch (IOException e) {  
  36.             e.printStackTrace();  
  37.         }  
  38.     }  
  39. }  

例子17:中文乱码的解决方案。

 
 
[java] view plain copy
  1. package cn.itheima.day05;  
  2. import java.io.UnsupportedEncodingException;  
  3. import java.util.Arrays;  
  4. public class EncodeDemo {  
  5.     public static void main(String[] args) throws UnsupportedEncodingException {  
  6.          String str = "你好";  
  7.          byte[] b1 = str.getBytes("GBK");   //编码  
  8.          //System.out.println(Arrays.toString(b1));  //Arrays.toString(b1)  把数组变成字符串  
  9.          String s1 = new String(b1,"ISO8859-1");   //要用指定编码表来解码  
  10.          //s1进行ISO8859-1编码  
  11.          byte[] b2 = s1.getBytes("ISO8859-1");  
  12.          System.out.println(Arrays.toString(b2));  //Arrays.toString(b2)  把数组变成字符串  
  13.          //解码  
  14.          String s2 = new String(b2,"GBK");  //解决方案,就是 编译一次,在解码一次  
  15.          //System.out.println(s1);  
  16.          System.out.println(s2);     
  17.     }  
  18. }  
例子18:记事本敲“联通”,再次打开出现乱码的问题。查看“联通”的二进制数是符合GBK的编码,还是符合UTF-8的编码。

 
 
[java] view plain copy
  1. package cn.itheima.day05;  
  2. import java.io.UnsupportedEncodingException;  
  3. public class EncodeDemo2 {  
  4.     public static void main(String[] args) throws UnsupportedEncodingException {  
  5.          String s = "联通";  
  6.          byte[] by = s.getBytes("GBK");  
  7.          for (byte b : by) {  
  8.             System.out.println(Integer.toBinaryString(b&255));  
  9.         }  
  10.     }  
  11. }  
例子19:有五名学生,每个学生有3门课的成绩,从键盘上输入以上数据,(包括姓名,和三门课的成绩,输出格式为:zhangsan,30,40,60,并且计算出总成绩,并把学生信息和计算出的总分数,按从高到低的顺序存放到硬盘的文件上”studentScore.txt”)
分析:1.描述学生对象。
          2.定义一个可操作学生对象的工具类。
思想:1.通过获得键盘上录入的一行数据,并将该行中的信息,取出封装成学生对象
         2.因为学生对象有很多,就需要使用集合,因为学生的总分要排序,所以可以使用TreeSet
         3.将集合中的信息写入到一个文件中。

 
 
[java] view plain copy
  1. package cn.itheima.day05;  
  2. import java.io.BufferedReader;  
  3. import java.io.BufferedWriter;  
  4. import java.io.FileWriter;  
  5. import java.io.IOException;  
  6. import java.io.InputStreamReader;  
  7. import java.util.Collections;  
  8. import java.util.Comparator;  
  9. import java.util.Set;  
  10. import java.util.TreeSet;  
  11. class Student implements Comparable<Student>{  
  12.     private String name;  
  13.     private int ma,cn,en;  
  14.     private int sum;  
  15.       
  16.     public String getName() {  
  17.         return name;  
  18.     }  
  19.     public int getSum() {  
  20.         return sum;  
  21.     }  
  22.     public int hashCode(){  
  23.         return name.hashCode()+sum*78;  
  24.     }  
  25.     public boolean equals(Object obj){  
  26.         if(!(obj instanceof Student))  
  27.             throw new ClassCastException("类型不匹配");  
  28.         Student s = (Student)obj;  
  29.         return this.name.equals(s.name) && this.sum==s.sum;  
  30.     }  
  31.     @Override  
  32.     public String toString() {  
  33.         return "Student [name=" + name + ", ma=" + ma + ", cn=" + cn + ", en="  
  34.                 + en + ", sum=" + sum + "]";  
  35.     }  
  36.     public Student(String name, int ma, int cn, int en) {  
  37.         super();  
  38.         this.name = name;  
  39.         this.ma = ma;  
  40.         this.cn = cn;  
  41.         this.en = en;  
  42.         sum = ma+cn+en;  
  43.     }  
  44.     @Override  
  45.     public int compareTo(Student s) {  
  46.         int num = new Integer(this.sum).compareTo(new Integer(s.sum));  
  47.         if(num==0)  
  48.             return this.name.compareTo(s.name);  
  49.         return num;  
  50.     }     
  51. }  
  52. class StudentInfoTool{  
  53.     public static Set<Student> getStudents() throws IOException{  
  54.         return getStudents(null);  
  55.     }  
  56.     public static Set<Student> getStudents(Comparator<Student> cmp) throws NumberFormatException, IOException{  
  57.         BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));  
  58.         String line = null;  
  59.         Set<Student> stus = null;  
  60.         if(cmp==null){  
  61.             stus=new TreeSet<Student>();   
  62.         }else {  
  63.             stus=new TreeSet<Student>(cmp);   
  64.         }     
  65.         while((line=bufr.readLine())!=null){  
  66.             if("over".equals(line))  
  67.                 break;  
  68.             String[] info= line.split(",");  
  69.             Student stu = new Student(info[0], Integer.parseInt(info[1]), Integer.parseInt(info[2]), Integer.parseInt(info[3]));  
  70.             stus.add(stu);  
  71.         }  
  72.         bufr.close();  
  73.         return stus;  
  74.       
  75.     public static void writeFile(Set<Student> stus) throws IOException{  
  76.         BufferedWriter bufw = new BufferedWriter(new FileWriter("F:\\Javajichu1\\JavaLianXi\\src\\cn\\itheima\\day05\\studentinfo.txt"));  
  77.         for (Student stu : stus) {  
  78.             bufw.write(stu.toString()+"\t");  
  79.             bufw.write(stu.getSum()+"");  
  80.             bufw.newLine();  
  81.             bufw.flush();  
  82.         }  
  83.         bufw.close();  
  84.     }  
  85. }  
  86. public class StudentInfoTest {  
  87.     public static void main(String[] args) throws NumberFormatException, IOException {  
  88.         Comparator<Student> cmp = Collections.reverseOrder();  
  89.         Set<Student> students = StudentInfoTool.getStudents(cmp);  
  90.         StudentInfoTool.writeFile(students);   
  91.     }  
  92. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值