• 黑马程序员——java学习12(毕20--21)——IO_2


    1、File

    1.1、增删判获

      1 package learn2;
      2 /*File类的常见方法:
      3  * 1、创建
      4  *     boolean createNewFile();//在指定位置创建如果,如果该文件已存在,则不创建,返回false;
      5  *                                     输出流会覆盖
      6  *     boolean mkdir();//创建文件夹
      7  *             mkdirs();//创建多级文件夹
      8  * 
      9  * 2、删除
     10  *     boolean delete();//删除失败,返回 false
     11  *     void deleteOnExit();//在程序退出时删除
     12  * 3、判断
     13  *     boolean exists();//文件是否存在
     14  *     isFile();
     15  *     isDirectory();
     16  *     isHidden();
     17  *     isAbsolute();测试此抽象路径名是否是绝对路径,即使不存在也可以判断
     18  *     
     19  * 4、获取信息
     20  *     getName();
     21  *     getPath();
     22  *     getParent();
     23  * 
     24  *     getAbsolutePath();
     25  *     long LastModify();
     26  *     long length();
     27  * 
     28  * */
     29 import java.io.File;
     30 import java.io.IOException;
     31 
     32 public class FileDemo {
     33     public static void main(String[] args) throws IOException{
     34         method_4();
     35     }
     36     public static void method_5()throws IOException
     37     {
     38         File f1 = new File("c:\test.java");
     39         File f2 = new File("c:\hahaha.java");
     40         sop("rename"+f1.renameTo(f2));
     41         
     42     }
     43     public static void method_4()throws IOException
     44     {
     45         File f = new File("c:\abc\a.txt");
     46         sop("path:"+f.getPath());//你封装的是什么路径,返回什么
     47         sop("abspath:"+f.getAbsolutePath());//无论封装的是什么。都返回其所属目录变绝对路径
     48         sop("parent:"+f.getParent());//该方法返回的是绝对路径中的文件父目录,如果获取相对路径,返回空
     49                                         //如果相对路径中有上一层目录。该目录则是返回结果
     50     }
     51     public static void method_3()throws IOException
     52     {
     53         File f = new File("file.txt");
     54         f.createNewFile();
     55         //记住,在判断文件对象是否是文件或者目录时,必须要先判断该文件对象封装的内容是否存在
     56         //通过exists判断
     57         sop("dir:"+f.isDirectory());
     58         sop("file:"+f.isFile());
     59         sop(f.isAbsolute());
     60     }
     61     public static void method_2()throws IOException
     62     {
     63         File f = new File("file.txt");
     64 //        sop("execute:"+f.canExecute());
     65         //创建文件夹
     66         File dir = new File("abc");
     67         //只能创建一级目录
     68 //        sop("mkdir:"+dir.mkdir());
     69         sop("mkdir:"+dir.mkdirs());
     70     }
     71     public static void method_1()throws IOException
     72     {
     73         File f= new File("file.txt");
     74         f.deleteOnExit();//在程序退出时删除
     75 //        sop("create:"+f.createNewFile());
     76         sop("delete:"+f.delete());
     77     }
     78     
     79     
     80     
     81     public static void consMethod()
     82     {
     83         //将a.txt封装成file对象,可以将已有的和未出现的文件或者文件夹封装成对象
     84         File f1= new File("a.txt");
     85         //
     86         File f2= new File("c:\abc","b.txt");
     87         
     88         File d = new File("c:\abc");
     89         File f3= new File(d,"c.txt");
     90         
     91         sop("f1:"+f1);
     92         sop("f2:"+f2);
     93         sop("f3:"+f3);
     94         
     95         File f4 = new File("c:"+File.separator+"abc\");
     96         
     97     }
     98     public static void sop(Object obj)
     99     {
    100         System.out.println(obj);
    101     }
    102 }

    1.2、文件列表

    调用list方法的对象,必须是真实存在的目录

    File[] listFiles(FilenameFilter filter)根据文件名过滤器过滤后得到的文件名数组

     1 package learn2;
     2 
     3 import java.io.File;
     4 import java.io.FilenameFilter;
     5 
     6 public class FileDemo2 {
     7     public static void main(String[] args) {
     8         File dir = new File("c:\");
     9         File[] files = dir.listFiles();
    10         for(File f:files)
    11         {
    12             System.out.println(f.getName()+"::"+f.length());
    13         }
    14     }
    15     public static void listDemo_2()
    16     {
    17         File dir = new File("c:\");
    18         //内部类
    19         String[] arr = dir.list(new FilenameFilter()
    20         {
    21             public boolean accept(File dir, String name)
    22             {    
    23 //                System.out.println("dir:"+dir);
    24 //                System.out.println("name:"+name);
    25 //                if(name.endsWith(".bmp"))
    26 //                    return true;
    27 //                else
    28 //                return false;
    29                 return name.endsWith(".bmp");
    30             }
    31         });
    32         System.out.println("leng:"+arr.length);
    33         for(String name:arr)
    34         {
    35             System.out.println(name);
    36         }
    37     }
    38     public static void listDemo()
    39     {
    40         File f = new File("c:\");
    41         String[] names = f.list();//包含隐藏文件,调用list的必须封装了一个真实存在的目录
    42         for(String name :names)
    43         {
    44             System.out.println(name);
    45         }
    46     }
    47     private static void listRootDemo() {
    48         // TODO Auto-generated method stub
    49         File[] files= File.listRoots();
    50         for(File f:files)
    51         {
    52             System.out.println(f);
    53         }
    54         
    55     }
    56 }

    运行结果为对应目录下的文件名数组

    1.3、列出目录下所有文件和文件夹&递归

    递归时注意限定条件,注意内存溢出

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

    1.4、删除文件夹及文件

    注意不能操作隐藏文件,否则返回空指针异常

     1 package learn2;
     2 
     3 import java.io.File;
     4 
     5 /*删除一个带内容过的目录
     6  * 原理
     7  * windows中,删除目录从里面往外删除的
     8  * 
     9  * 既然是从里往外删除,就需要用到递归
    10  * 
    11  * */
    12 public class RemoveDir {
    13     public static void main(String[] args) {
    14         File dir = new File("F:\test");
    15         removeDir(dir);
    16     }
    17     public static void removeDir(File dir)
    18     {
    19         File[] files =dir.listFiles();
    20         for(int x=0;x<files.length;x++)
    21         {
    22             if(!files[x].isHidden()&&files[x].isDirectory())
    23                 removeDir(files[x]);
    24             else 
    25                 //判断有没删错,打印一下看看
    26                 System.out.println(files[x].toString()+":-file-:"+files[x].delete());
    27             
    28         }
    29         System.out.println(dir+"::dir::"+dir.delete());
    30     }
    31 }

    运行结果

    1.5、创建java文件列表

     1 package learn2;
     2 
     3 import java.io.BufferedWriter;
     4 import java.io.File;
     5 import java.io.FileWriter;
     6 import java.io.IOException;
     7 import java.util.ArrayList;
     8 import java.util.List;
     9 
    10 /*
    11  * 将一个指定目录下的java文件的绝对路径,存储到一个文本文件中
    12  * 建立一个java文件列表文件
    13  * 
    14  * 思路
    15  * 1、对指定目录递归
    16  * 2、获取递归过程中所有java文件路径
    17  * 3、将这些路径存储到集合中
    18  * 4、将集合中的数据写入到一个文件中
    19  * */
    20 public class JavaFileList {
    21     public static void main(String[] args) throws IOException
    22     {
    23         File dir = new File("D:\Workspaces\MyEclipse 10\day14IO");
    24         List<File> list = new ArrayList<File>();
    25         fileToList(dir,list);
    26 //        System.out.println(list.size());
    27         File file = new File(dir,"JavaFileList.txt");
    28         writeToFile(list,file.toString());
    29     }
    30     public static void fileToList(File dir,List<File>list)
    31     {
    32         File[] files = dir.listFiles();
    33         for(File file:files)
    34         {
    35             if(file.isDirectory())
    36                 fileToList(file,list);
    37             else
    38             {
    39                 if(file.getName().endsWith(".java"))
    40                     list.add(file);
    41             }
    42         }
    43     }
    44     public static void writeToFile(List<File> list,String javaListFile) throws IOException
    45     {
    46         BufferedWriter bufw = null;
    47         try
    48         {
    49             bufw = new BufferedWriter(new FileWriter(javaListFile));
    50             for(File f:list)
    51             {
    52                 String path = f.getAbsolutePath();
    53                 bufw.write(path);
    54                 bufw.newLine();
    55                 bufw.flush();
    56             }
    57         }
    58         catch(IOException e)
    59         {
    60             throw e;//或者抛runtimeE
    61         }
    62         finally
    63         {
    64             try
    65             {
    66                 if(bufw!=null)
    67                     bufw.close();
    68             }
    69             catch(IOException e)
    70             {
    71                 throw e;
    72             }
    73         }
    74     }
    75 }

    运行结果

    1.6、Properties存取配置

    存入格式为

    键=值

     1 package learn2;
     2 
     3 import java.io.BufferedReader;
     4 import java.io.FileInputStream;
     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 /*
    12  * Properties是hashtable的子类
    13  * 也就是说它具备map集合的特点。而且它里面存储的键值都是字符串
    14  * 是集合中和IO技术相结合的集合容器
    15  * 该对象的特点:可以用于键值对形式的配置文件
    16  * 固定格式  键=值
    17  * */
    18 public class PropertiesDemo {
    19     public static void main(String[] args) throws IOException{
    20         loadDemo();
    21     }
    22     public static void loadDemo()throws IOException
    23     {
    24         Properties prop = new Properties();
    25         FileInputStream fis =new FileInputStream("info.txt");
    26         prop.load(fis);
    27         prop.setProperty("wangwu", "39");
    28         FileOutputStream fos = new FileOutputStream("info.txt");
    29         prop.store(fos, "haha");
    30 //        System.out.println(prop);
    31         prop.list(System.out);
    32         fos.close();
    33         fis.close();
    34     }
    35     
    36     //想要将流中的数据存储到集合中
    37     //想要将into.txt中键值数据存到集合中进行操作
    38     /*
    39      * 1.用一个流和info.txt文件关联
    40      * 2、读取一行数据,将该行数据用"="进行切割
    41      * 3、等号左边作为键,右边作为值,存入到Properties集合中即可
    42      * */
    43     public static void method_1()throws IOException
    44     {
    45         BufferedReader bufr= new BufferedReader(new FileReader("info.txt"));
    46         String line = null;
    47         Properties prop = new Properties();
    48         while((line = bufr.readLine())!=null)
    49         {
    50             String[]arr = line.split("=");
    51 //            System.out.println(line);
    52             prop.setProperty(arr[0], arr[1]);
    53         }
    54         bufr.close();
    55         System.out.println(prop);
    56     }
    57     //设置和获取元素
    58     public static void setAndGet()
    59     {
    60         Properties prop = new Properties();
    61         prop.setProperty("zhangsan", "30");
    62         prop.setProperty("lisi", "39");
    63 //        System.out.println(prop);
    64         String value = prop.getProperty("lisi");
    65 //        System.out.println(value);
    66         prop.setProperty("lisi", 89+"");
    67         Set<String> names = prop.stringPropertyNames();
    68         for(String s:names)
    69         {
    70             System.out.println(s+":"+prop.getProperty(s));
    71         }
    72     }
    73 }

    1.7、配置文件应用-计算使用次数

     1 package learn2;
     2 
     3 import java.io.File;
     4 import java.io.FileInputStream;
     5 import java.io.FileOutputStream;
     6 import java.io.IOException;
     7 import java.util.Properties;
     8 
     9 /*
    10  * 用于记录应用程序运行次数,
    11  * 如果使用次数已到,那么给出注册提示
    12  * 
    13  * 易想到:计数器
    14  * 可是该计数器定义在程序中,随着程序的运行而在内存中存在,并进行自增
    15  * 可是随着该应用程序的退出,该计数器也在内存中消失了
    16  * 下一次再启动改程序,又重新开始从0计数
    17  * 所以建立配置文件,下次使用会先加载然后+1
    18  * 
    19  * 该配置文件使用键值对形式。是map集合。
    20  * 数据是文件形式存储,使用IO技术,IO+MAP-->properties
    21  * 
    22  * */
    23 public class RunCount {
    24     public static void main(String[] args) throws IOException{
    25         Properties prop = new Properties();
    26         
    27 //        先把文件封装成对象
    28         File file = new File("count.ini");
    29         if(!file.exists())//如果文件不存在
    30             file.createNewFile();
    31         FileInputStream fis = new FileInputStream(file);
    32         prop.load(fis);
    33         int count=0;
    34         String value = prop.getProperty("time");
    35         if(value!=null)
    36         {
    37             count=Integer.parseInt(value);
    38             if(count>5)
    39             {
    40                 System.out.println("您好,使用次数已到,拿钱!");
    41             }
    42         }
    43         count++;
    44         prop.setProperty("time", count+"");
    45         FileOutputStream fos = new FileOutputStream(file);
    46         prop.store(fos, "");
    47         fos.close();
    48         fis.close();
    49     }
    50 }

    运行结果

    1.8、打印流

    package learn2;
    
    import java.io.BufferedReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    
    /*
     * 打印流:
     * 该流提供了打印方法,可以将各种数据类型的数据都原样打印
     * 字节打印流
     * PrintStream
     * 构造函数可以接收的参数类型:
     * 1、file 对象 File 
     * 2、字符串路径 String 
     * 3、字节输出流 OutputStream
     * PrintWriter
     * 1、file 对象 File 
     * 2、字符串路径 String 
     * 3、字节输出流 OutputStream
     * 4、字符输出流 Writer
     * */
    public class PrintSystreamDemo {
        public static void main(String[] args)throws IOException {
            BufferedReader bufr = 
                    new BufferedReader(new InputStreamReader(System.in));
            PrintWriter out = new PrintWriter(new FileWriter("a.txt"),true);
            String line =null;
            while((line=bufr.readLine())!=null)
            {
                if("over".equals(line))
                    break;
                out.println(line.toUpperCase());
                //有println和true才可刷
    //            out.flush();
            }
            out.close();
            bufr.close();
        }
    }

    1.9、多个文件组合成一个,并输出

     1 package learn2;
     2 
     3 import java.io.FileInputStream;
     4 import java.io.FileOutputStream;
     5 import java.io.IOException;
     6 import java.io.SequenceInputStream;
     7 import java.util.Enumeration;
     8 import java.util.Vector;
     9 
    10 public class SequenceDemo {
    11     public static void main(String[] args) throws IOException{
    12         //文件存入流,存入集合中
    13         Vector<FileInputStream> v = new Vector<FileInputStream>();
    14         v.add(new FileInputStream("D:\Workspaces\MyEclipse 10\day14IO\1.txt"));
    15         v.add(new FileInputStream("D:\Workspaces\MyEclipse 10\day14IO\2.txt"));
    16         v.add(new FileInputStream("D:\Workspaces\MyEclipse 10\day14IO\3.txt"));
    17         //输出vector中所有元素
    18         Enumeration<FileInputStream> en = v.elements();
    19         //多个流变成了一个流
    20         SequenceInputStream sis = new SequenceInputStream(en);
    21         FileOutputStream fos = new FileOutputStream("D:\Workspaces\MyEclipse 10\day14IO\4.txt");
    22         //源和目的的读写操作
    23         byte[] buf = new byte[1024];
    24         int len =0;
    25         while((len=sis.read(buf))!=-1)
    26         {
    27             fos.write(buf,0,len);
    28         }
    29         fos.close();
    30         sis.close();
    31     }
    32     
    33     
    34 }

    1.10、文件切割和合并

     1 package learn2;
     2 
     3 import java.io.FileInputStream;
     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 import java.util.Iterator;
    10 
    11 public class SplitFile {
    12     public static void main(String[] args)throws IOException {
    13         merge();
    14         
    15     }
    16     public static void merge()throws IOException
    17     {
    18         ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
    19         for(int x=1;x<4;x++)
    20         {
    21             al.add(new FileInputStream("C:\spilitifiles\"+x+".part"));
    22         }
    23         final Iterator<FileInputStream> it = al.iterator();
    24         Enumeration<FileInputStream> en = new Enumeration<FileInputStream>()
    25         {
    26             public boolean hasMoreElements()
    27             {
    28                 return it.hasNext();
    29             }
    30             public FileInputStream nextElement()
    31             {
    32                 return it.next();
    33             }
    34         };
    35         SequenceInputStream sis = new SequenceInputStream(en);
    36         FileOutputStream fos = new FileOutputStream("C:\spilitifiles\0.mp3");
    37         byte[] buf = new byte[1024];
    38         int len = 0;
    39         while((len=sis.read(buf))!=-1)
    40         {
    41             fos.write(buf,0,len);
    42         }
    43         fos.close();
    44         sis.close();
    45     }
    46     public static void splitFile()throws IOException
    47     {
    48         FileInputStream fis= new FileInputStream("c:\3.mp3");
    49         FileOutputStream fos = null;
    50         
    51         byte[] buf = new byte[1024*1024];
    52         
    53         int len = 0;
    54         int count = 1;
    55         while((len=fis.read(buf))!=-1)
    56         {
    57             //已经不是完成文件了,扩展名为part或任意
    58             fos = new FileOutputStream("C:\spilitifiles\"+(count++)+".part");
    59             fos.write(buf,0,len);
    60             fos.close();
    61             
    62         }
    63         if(fos!=null)
    64             fos.close();
    65         fis.close();
    66     }
    67 }

    运行结果

    2、

    2.1、对象的序列化

    ObjectOutputStream读,则必须是ObjectInputStream写的,否则无法读出

    java.io.NotSerializableException;查看是否实现标号接口implements Serializable

    此类内可自行添加序列号,也可以通过transient、static来防止修改文件,

     1 package learn3;
     2 
     3 import java.io.FileInputStream;
     4 import java.io.FileOutputStream;
     5 import java.io.IOException;
     6 import java.io.ObjectInputStream;
     7 import java.io.ObjectOutputStream;
     8 
     9 public class ObjectStreamDemo {
    10     public static void main(String[] args) throws IOException, ClassNotFoundException{
    11         readObj();
    12 //        writeObj();
    13     }
    14     public static void readObj()throws IOException, ClassNotFoundException
    15     {
    16         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));
    17         Person p =(Person)ois.readObject();
    18         System.out.println(p);
    19         ois.close();
    20     }
    21     public static void writeObj() throws IOException
    22     {
    23         ObjectOutputStream oos = 
    24                 new ObjectOutputStream(new FileOutputStream("obj.txt"));
    25         oos.writeObject(new Person("lisi",39,"kr"));
    26         oos.close();
    27     }
    28 }

    其中Person

     1 package learn3;
     2 
     3 import java.io.Serializable;
     4 
     5 //没有方法的接口,标记接口,
     6 //为了实现序列化,实现了标记接口,序列化的是堆内存
     7 public class Person implements Serializable {
     8     //自定义序列号
     9     public static final long serialVersionUID = 42;
    10     String name;
    11     //保证值在堆内存中存在而不在文本文件
    12     transient int age;
    13     static String country ="cn";
    14     Person(String name,int age,String country)
    15     {
    16         this.name=name;
    17         this.age=age;
    18         this.country=country;
    19     }
    20     public String toString()
    21     {
    22         return name+":"+age+":"+country;
    23     }
    24 }

    运行结果

    2.2、管道流

    read其实是一种阻塞式的方法,没有数据时都得等

     1 package learn3;
     2 
     3 import java.io.IOException;
     4 import java.io.PipedInputStream;
     5 import java.io.PipedOutputStream;
     6 
     7 /*
     8  * 
     9  * */
    10 class Read implements Runnable
    11 {
    12     private PipedInputStream in;
    13     Read(PipedInputStream in)
    14     {
    15         this.in=in;
    16     }
    17     public void run()
    18     {
    19         try
    20         {
    21             byte[] buf = new byte[1024];
    22             //阻塞式的方法read,没有数据都得等
    23             int len =in.read(buf);
    24             String s = new String(buf,0,len);
    25             System.out.println(s);
    26             in.close();
    27         }
    28         catch(IOException e)
    29         {
    30             throw new RuntimeException("管道读取流失败");
    31         }
    32     }
    33 }
    34 class Write implements Runnable
    35 {
    36     private PipedOutputStream out;
    37     Write(PipedOutputStream out)
    38     {
    39         this.out=out;
    40     }
    41     public void run()
    42     {
    43         try
    44         {
    45             out.write(("pipedlaila".getBytes()));
    46             out.close();
    47         }
    48         catch(IOException e)
    49         {
    50             throw new RuntimeException("管道输出流失败");
    51         }
    52     }
    53 }
    54 public class PipedStreamDemo {
    55     public static void main(String[] args) throws IOException{
    56         PipedInputStream in = new PipedInputStream();
    57         PipedOutputStream out = new PipedOutputStream();
    58         //相接
    59         in.connect(out);
    60         Read r = new Read(in);
    61         Write w = new Write(out);
    62         new Thread(r).start();
    63         new Thread(w).start();
    64     }
    65 }

    运行结果

    2.3、随机读取访问

     1 package learn3;
     2 
     3 import java.io.IOException;
     4 import java.io.RandomAccessFile;
     5 
     6 /*
     7  * RandomAccessFileDemo
     8  * 该类不算是IO体系中的子类
     9  * 而是直接继承自Object
    10  * 但是它是IO包中成员。因为它具备读和写功能。
    11  * 内部封装了一个byte数组,而且通过指针对数组的元素进行操作
    12  * 可以通过getFilePointer获取指针位置
    13  * 同时通过seek改变指针位置
    14  * 其实完成读写的原理就是内部封装了字节输入流和输出流
    15  * 
    16  * 通过构造函数看出只能操作文件
    17  * 且操作文件有模式选择
    18  * 如果R模式,不会创建文件。会去读取一个已存在文件,如果该文件不存在,则会出现异常
    19  * 如果RW模式,操作的文件不存在,会自动创建,如果存在则不会覆盖
    20  * 
    21  * */
    22 public class RandomAccessFileDemo {
    23     public static void main(String[] args)throws IOException {
    24         writeFile_2();
    25 //        readFile();
    26         RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");
    27         raf.write("haha".getBytes());
    28         
    29     }
    30     public static void readFile()throws IOException
    31     {
    32         RandomAccessFile raf = new RandomAccessFile("ran.txt","r");
    33         //调整对象中指针
    34 //        raf.seek(8*0);
    35         //跳过指定的字节数
    36         raf.skipBytes(8);
    37         byte[] buf = new byte[4];
    38         raf.read(buf);
    39         String name = new String(buf);
    40         int age = raf.readInt();
    41         System.out.println("name:"+name);
    42         System.out.println("age:"+age);
    43         raf.close();
    44     }
    45     public static void writeFile_2() throws IOException
    46     {    
    47         RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");
    48         raf.seek(8*3);
    49         raf.write("周期".getBytes());
    50         raf.writeInt(103);
    51     }
    52     public static void writeFile()throws IOException
    53     {    
    54         RandomAccessFile raf = new RandomAccessFile("ran.txt","rw");
    55         raf.write("李四".getBytes());
    56         //强转时会添加三个空格
    57         raf.writeInt(97);
    58         raf.write("王五".getBytes());
    59         raf.writeInt(99);
    60         raf.close();
    61         
    62     }
    63 }

    2.4、基本数据类型流的操作

     1 package learn3;
     2 
     3 import java.io.DataInputStream;
     4 import java.io.DataOutputStream;
     5 import java.io.FileInputStream;
     6 import java.io.FileOutputStream;
     7 import java.io.IOException;
     8 import java.io.OutputStreamWriter;
     9 
    10 /*
    11  * DateInputStream与DateOutputStream
    12  * 可以操作基本数据类型的流对象
    13  * */
    14 public class DateStreamDemo {
    15     public static void main(String[] args)throws IOException {
    16         writeUTFDemo();
    17         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("gbk.txt"),"gbk");
    18         osw.write("你好");
    19         osw.close();
    20     }
    21     public static void readUTFDemo() throws IOException
    22     {
    23         DataInputStream dis = new DataInputStream(new FileInputStream("utfdate.txt"));
    24         String s = dis.readUTF();
    25         System.out.println(s);
    26         dis.close();
    27     
    28     }
    29     public static void writeUTFDemo() throws IOException
    30     {
    31         DataOutputStream dos = new DataOutputStream(new FileOutputStream("utfdate.txt"));
    32         dos.writeUTF("你好");
    33         dos.close();
    34     }
    35     public static void readData()throws IOException
    36     {
    37         DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
    38         int num = dis.readInt();
    39         boolean b = dis.readBoolean();
    40         double d = dis.readDouble();
    41         System.out.println("num:"+num);
    42         System.out.println("b:"+b);
    43         System.out.println("d:"+d);
    44         dis.close();
    45     }
    46     public static void writeData()throws IOException
    47     {
    48         DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
    49         dos.writeInt(234);
    50         dos.writeBoolean(true);
    51         dos.writeDouble(9887.543);
    52         
    53         dos.close();
    54     }
    55 }

    2.5、ByteArrayStream

     1 package learn3;
     2 
     3 import java.io.ByteArrayOutputStream;
     4 import java.io.ByteArrayInputStream;
     5 
     6 /*
     7  * 用于操作字节数组的流对象
     8  * ByteArrayInputStream:在构造的时候,需要接受数据源,而且数据源是一个字节数组
     9  * ByteArrayOutputStream:在构造的时候,不用定义数据目的,因为该对象中已经封装了可变长度的字节数组。
    10  * 这就是数据目的地
    11  * 
    12  * 因为这两个流对象都操作的数组,并没有使用系统资源
    13  * 所以,不用进行close关闭。
    14  * 
    15  * 在流操作规律讲解时,
    16  * 源设备
    17  *     键盘system.in,硬盘FileStream,内存ArrayStream
    18  * 目的设备
    19  *     控制台system.out,硬盘FileStream,内存ArrayStream
    20  * 用流的读写思想操作数组
    21  * */
    22 public class ByteArrayInputStreamDemo {
    23     public static void main(String[] args) {
    24         //数据源
    25         ByteArrayInputStream bis = new ByteArrayInputStream("ABCDEF".getBytes());
    26         //数据目的
    27         ByteArrayOutputStream bos = new ByteArrayOutputStream();
    28         
    29         int by = 0;
    30         
    31         while((by=bis.read())!=-1)
    32         {
    33             bos.write(by);
    34         }
    35         
    36         System.out.println(bos.size());
    37         System.out.println(bos.toString());
    38     }
    39 }

    2.6、字符编码

     2.6.1、转换流

    你好 出??G编码 U8解码

       出浣豺U8编码 GBK解码

     1 package learn3;
     2 
     3 import java.io.FileInputStream;
     4 import java.io.FileOutputStream;
     5 import java.io.IOException;
     6 import java.io.InputStreamReader;
     7 import java.io.OutputStreamWriter;
     8 
     9 public class EncodeStream {
    10     public static void main(String[] args)throws IOException {
    11 //        writeText();
    12         readText();
    13     }
    14     public static void readText()throws IOException
    15     {
    16         InputStreamReader isr = new InputStreamReader(new FileInputStream("gbk.txt"),"GBK");
    17         char[] buf = new char[10];
    18         int len = isr.read(buf);
    19         String str = new String(buf,0,len);
    20         System.out.println(str);
    21         isr.close();
    22     }
    23     public static void writeText()throws IOException
    24     {
    25         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("gbk.txt"));//"uft.txt",UTF-8
    26         osw.write("你好");
    27         
    28         osw.close();
    29     }
    30 
    31 }

    2.6.2、字符编码,错误的处理

     1 package learn3;
     2 
     3 import java.io.IOException;
     4 import java.util.Arrays;
     5 
     6 /*
     7  * 编码:字符串变成字节数组
     8  * 
     9  * 解码:字节数组变成字符串
    10  * String-->byte; str.getbytes(charsetName);
    11  * byte[]-->String: new String(byte[],charsetName);
    12  * */
    13 public class EncodeDemo {
    14     public static void main(String[] args)throws IOException {
    15         String s = "你好";
    16         byte[] b1 = s.getBytes("GBK");
    17         String s1 = new String(b1,"ISO8859-1");//若u8则易出问题,中文解错不易解
    18         System.out.println("s1="+s1);
    19         
    20         //对S1进行ISO8859-1编码
    21          byte[] b2 = s1.getBytes("iso8859-1");
    22          System.out.println(Arrays.toString(b2));
    23          String s2 = new String(b2,"gbk");
    24          System.out.println("s2="+s2);
    25         
    26 //        System.out.println(Arrays.toString(b1));
    27         
    28     }
    29 }

    运行结果

    2.6.3、联通

    往前面加中文即可

     1 package learn3;
     2 
     3 import java.io.IOException;
     4 
     5 public class EncodeDemo2 {
     6     public static void main(String[] args) throws IOException{
     7         String s = "联通";
     8         byte[] by = s.getBytes("gbk");
     9         for(byte b:by)
    10         {
    11             System.out.println(Integer.toBinaryString(b&255));
    12         }
    13     }
    14 }

    2.6.4、练习

      1 package Test;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.BufferedWriter;
      5 import java.io.FileWriter;
      6 import java.io.IOException;
      7 import java.io.InputStreamReader;
      8 import java.util.Collections;
      9 import java.util.Comparator;
     10 import java.util.Set;
     11 import java.util.TreeSet;
     12 
     13 /*
     14  *有五个学生,每个学生有3门课的成绩
     15  *从键盘输入以上数据(包括姓名,三门课成绩)
     16  *输入的格式,如:zhangsan,30,40,60计算出总成绩
     17  *并把学生的信息和计算出的总分数高低排序存放在磁盘文件"stud.txt"中
     18  *
     19  * 1、描述学生对象
     20  * 2、定义一个可以操作学生对象的工具类
     21  * 
     22  * 思想:
     23  * 1、通过获取键盘录入的一行数据,并将改行数据中的信息取出,封装成学生对象
     24  * 2、因为学生对象有很多,那么就需要存储,使用到集合,因为要对学生的总分排序,
     25  * 所以可以使用TreeSet
     26  * 3、将集合中的信息写入到一个文件中
     27  * */
     28 
     29 class Student implements Comparable<Student>
     30 {
     31     private String name;
     32     private int ma,cn,en;
     33     private int sum;
     34     Student(String name,int ma,int cn, int en)
     35     {
     36         this.name=name;
     37         this.ma=ma;
     38         this.cn=cn;
     39         this.en=en;
     40         sum = ma+cn+en;
     41     }
     42     //实现了comparable,所以判断比较方法,compareTo方法是类,所以Integer包装一下
     43     public int compareTo(Student s)
     44     {
     45         int num =new Integer(this.sum).compareTo(new Integer(s.sum));
     46         if(num==0)
     47             return this.name.compareTo(s.name);
     48         return num;
     49     }
     50     public String getName()
     51     {
     52         return name;
     53     }
     54     public int getSum()
     55     {
     56         return sum;
     57     }
     58     public int hashCode()
     59     {
     60         return name.hashCode()+sum*78;
     61     }
     62     public boolean equals(Object obj)
     63     {
     64         if(!(obj instanceof Student))
     65             throw new ClassCastException("类型不匹配");
     66         Student s = (Student)obj;
     67             return this.name.equals(s.name)&&this.sum==s.sum;
     68     }
     69     public String toString()
     70     {
     71         return "student["+name+", "+ma+", "+cn+", "+en+"]";
     72     }
     73 }
     74 
     75 class StudentInfoTool
     76 {
     77     //没有比较器的
     78     public static Set<Student> getStudents()throws IOException
     79     {
     80         return getStudents(null);
     81     }
     82     //有比较器的
     83     public static Set<Student> getStudents(Comparator<Student> cmp)throws IOException
     84     {
     85         BufferedReader bufr =
     86                 new BufferedReader(new InputStreamReader(System.in));
     87         String line = null;
     88         Set<Student> stus =null;
     89         if(cmp==null)
     90             stus = new TreeSet<Student>();
     91         else
     92             stus = new TreeSet<Student>(cmp);
     93         while((line = bufr.readLine())!=null)
     94         {
     95             if("over".equals(line))
     96                 break;
     97             String[] info = line.split(",");
     98             Student stu = new Student(info[0],Integer.parseInt(info[1]),
     99                     Integer.parseInt(info[2]),
    100                     Integer.parseInt(info[3]));
    101             stus.add(stu);
    102         }
    103         bufr.close();
    104         return stus;
    105     }
    106     public static void write2File(Set<Student> stus)throws IOException
    107     {
    108         //定义数据存储位置
    109         BufferedWriter bufw =new BufferedWriter(new FileWriter("stuInfo.txt"));
    110         for(Student stu:stus)
    111         {
    112             bufw.write(stu.toString()+"	");
    113             //别忘记+""转型
    114             bufw.write(stu.getSum()+"");
    115             bufw.newLine();
    116             bufw.flush();
    117         }
    118         bufw.close();
    119     }
    120 }
    121 public class StudentInfoTest {
    122     public static void main(String[] args)throws IOException {
    123         //强行逆转比较器
    124         Comparator<Student> cmp = Collections.reverseOrder();
    125         Set<Student> stus = StudentInfoTool.getStudents(cmp);
    126         StudentInfoTool.write2File(stus);
    127     }
    128 }

    运行结果

  • 相关阅读:
    Android 自定义Dialog中加EditText弹不出键盘跟Dialog遮挡键盘的问题
    上周热点回顾(8.28-9.3)团队
    云计算之路-阿里云上-新车限行:新购服务器无法访问任何远程25端口团队
    上周热点回顾(8.21-8.27)团队
    云计算之路-阿里云上-容器难容:自建docker swarm集群遭遇无法解决的问题团队
    上周热点回顾(8.14-8.20)团队
    上周热点回顾(8.7-8.13)团队
    上周热点回顾(7.31-8.6)团队
    上周热点回顾(7.24-7.30)团队
    故障公告:docker swarm集群“群龙无首”造成部分站点无法访问团队
  • 原文地址:https://www.cnblogs.com/sunxlfree1206/p/4716800.html
Copyright © 2020-2023  润新知