• JavaSE-IO流


    package com.btp.t4;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Date;
    
    import org.junit.Test;
    
    /*
     * java.io.File
     * 1.凡是与输入,输出相关的类,接口等都定义在java.io包下
     * 2.File是一个类,可以有构造器创建其对象。此对象对应着一个文件(.txt .avi .doc .ppt .mp3 .jpg)或文件目录
     * 3.File类对象是与平台无关的
     * 4.File中的方法,仅涉及到如何创建,删除,重命名等等.只要涉及文件内容,File是无能为力的,必须由io流来完成
     * 5.File类的对象常作为io流的具体类的构造器的形参
     * 
     *    getName()
     *    getPath()
     *    getAbsoluteFile()
     *    getAbsolutePath()
     *    getParent()
     *    renameTo(File newName)
     *    
     *    exists()
     *    canWrite()
     *    canRead()
     *    isFile()
     *    isDirectory()
     *    lastModified()
     *    length()
     *    
     *    createNewFile()
     *    delete()
     *    mkDir():上层目录存在的情况下,创建一个文件目录
     *    mkDirs():上层目录不存在,连上层目录一起创建
     *    list():打印出所在路径所有的文件名,以String[]的形式返回
     *    listFiles():以File[]的形式返回路径下所有的文件
     */
    public class TestFile {
        /*
         * 路径:
         * 绝对路径:包括盘符在内的完整的文件路径
         * 相对路径:在当前文件目录下的文件的路径
         */
        @Test
        public void test3() throws IOException
        {
            File f1=new File("C:\Users\kobefan1\Desktop\io\helloworld.txt");
            f1.delete();
            if(!f1.exists()){
                System.out.println(f1.createNewFile());
            }
            File f2=new File("C:\Users\kobefan1\Desktop\io\io2");
            if(!f2.exists()){
                System.out.println(f2.mkdir());
            }
            System.out.println();
            
            File f3=new File("C:\Users\kobefan1\Desktop");
            String[] str=f3.list();
            for(Object obj:str){
                System.out.println(obj);
            }
            System.out.println();
            
            File[] str1=f3.listFiles();
            for(File obj:str1){
                System.out.println(obj.getName());
            }
        }
        
        @Test
        public void test2()
        {
            File f1=new File("C:\Users\kobefan1\Desktop\io\helloworld.txt");
            File f2=new File("C:\Users\kobefan1\Desktop\io\io1");
            System.out.println(f1.exists());
            System.out.println(f1.canWrite());
            System.out.println(f1.canRead());
            System.out.println(f1.isFile());
            System.out.println(f1.isDirectory());
            System.out.println(new Date(f1.lastModified()));
            System.out.println(f1.length());
            
            System.out.println();
            
            System.out.println(f2.exists());
            System.out.println(f2.canWrite());
            System.out.println(f2.canRead());
            System.out.println(f2.isFile());
            System.out.println(f2.isDirectory());
            System.out.println(f2.lastModified());
            System.out.println(f2.length());
        }
        
        @Test
        public void test1()
        {
            File f1=new File("C:\Users\kobefan1\Desktop\io\helloworld.txt");
            File f2=new File("hello1.txt");
            
            File f3=new File("C:\Users\kobefan1\Desktop\io\io1");
            System.out.println(f1.getName());
            System.out.println(f1.getPath());
            System.out.println(f1.getAbsoluteFile());
            System.out.println(f1.getParent());
            System.out.println(f1.getAbsolutePath());
            
            System.out.println();
            
            System.out.println(f3.getName());
            System.out.println(f3.getPath());
            System.out.println(f3.getAbsoluteFile());
            System.out.println(f3.getParent());
            System.out.println(f3.getAbsolutePath());
            
            // renameTo(File newName):重命名
            //file1.renameTo(file2):file1重命名为file2.要求:file1一定存在,file2一定不存在
            System.out.println(f1.renameTo(f2));
        }
    }
    File
    package com.btp.t4;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import org.junit.Test;
    
    /*
     * 1.流的分类
     * 按照数据流向的不同:输入流,输出流
     * 按照处理数据的单位的不同:字节流,字符流(处理文本文件)
     * 按照角色的不同:节点流(直接作用于文件的),处理流
     * 2. IO的体系
     * 抽象基类                                                                     节点流(文件流)                                        缓冲流(处理流的一种,效率更高)
     * InputStream(处理字节流)            FileInputStream                   BufferedInputStream         
     * OutputStream(处理字节流)          FileOutputStream              BufferedOutputStream
     * Reader(处理字符流)                FileReader(处理文本文件)               BufferedReader
     * Writer(处理字符流)                FileWriter(处理文本文件)               BufferedWriter
     */
    public class TestFileInputOutputStream {
        public static void main(String[] args){
            TestFileInputOutputStream.copyFile("C:\Users\kobefan1\Desktop\adoub.jpg", "C:\Users\kobefan1\Desktop\adoub1.jpg");
        }
        
        
        //实现文件复制的方法
        public static void copyFile(String str1,String str2)
        {
            //从硬盘中读取一个文件,并写入到另一个位置。(相当于文件的复制)
                    //1.提供读入,写出的文件
                    File file1=new File(str1);
                    File file2=new File(str2);
                    //2.提供相应的流的对象
                    FileInputStream fis=null;
                    FileOutputStream fos=null;
                    
                    try {
                        fis=new FileInputStream(file1);
                        fos=new FileOutputStream(file2);
                        //实现文件的复制
                        byte[] b=new byte[20];
                        int len;
                        while((len=fis.read(b))!=-1){
                            //fos.write(b);//错误的写法,和fos.write(b,0,b.length);一样的效果
                            fos.write(b, 0, len);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //关闭相应的流
                    finally{
                        try {
                            fis.close();
                        } catch (IOException e) {
                            // TODO 自动生成的 catch 块
                            e.printStackTrace();
                        }
                        try {
                            fos.close();
                        } catch (IOException e) {
                            // TODO 自动生成的 catch 块
                            e.printStackTrace();
                        }
                    }
        }
        
        
        @Test
        public void testFileInputOutputStream(){
            //从硬盘中读取一个文件,并写入到另一个位置。(相当于文件的复制)
            //1.提供读入,写出的文件
            File file1=new File("C:\Users\kobefan1\Desktop\adoub.jpg");
            File file2=new File("adoub.txt");
            //2.提供相应的流的对象
            FileInputStream fis=null;
            FileOutputStream fos=null;
            
            try {
                fis=new FileInputStream(file1);
                fos=new FileOutputStream(file2);
                //实现文件的复制
                byte[] b=new byte[20];
                int len;
                while((len=fis.read(b))!=-1){
                    //fos.write(b);//错误的写法,和fos.write(b,0,b.length);一样的效果
                    fos.write(b, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //关闭相应的流
            finally{
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
                try {
                    fos.close();
                } catch (IOException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
            }
        }
        
        
        //FileOutputStream
        @Test
        public void testFileOutputStream1(){
            //1.创建一个File对象,表明要写入的文件位置,文件可以不存在,自动帮你创建 。若存在,会将原有的文件覆盖。
            File file = new File("hello1.txt");
            //2.创建一个FileOutputStream对象,将File对象作为形参传递给FileOutputStream的构造器中
            FileOutputStream fos=null;
            
            try {
                fos=new FileOutputStream(file);
                //3.写入操作
                fos.write(new String("I love China,I love world").getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            finally{
                //4.关闭输出流
                try {
                    fos.close();
                } catch (IOException e) {
                    // TODO 自动生成的 catch 块
                    e.printStackTrace();
                }
            }
        }
        
        
        
        
        //从硬盘存在的一个文件中读取其内容到程序中,使用FileInputStream
        //要读取的文件一定要存在。否则抛FileNotFoundException
        
        @Test
        public void testFileInputStream3() throws IOException{
            File file=new File("hello.txt");
            FileInputStream fis=new FileInputStream(file);
            byte[] b=new byte[20];//读取到的数据要写入的数组
            int len;//每次要读写入byte的字节的长度
            while((len=fis.read(b))!=-1){//每次从文件中读取b.length个字节,如果少于b.length,则有多少读多少,读完返回每次读取的个数
                
                for(int i=0;i<len;i++){//b.length是20,所以要写成len
                    System.out.println((char)b[i]);//把数组b中的打印出来,len是真实读入的字节个数
                }
            }
            fis.close();
        }
        
        
        
        //使用try-catch的方式处理如下异常更合适:保证流的关闭操作一定可以执行
        @Test
        public void testFileInputStream2(){
                    FileInputStream fis=null;//声明在外面,使finally语句内也可以调用
                    try {
                        //1.创建一个File类的对象
                        File file=new File("hello.txt");
                        //2.创建一个FileInputStream类的对象
                        fis=new FileInputStream(file);
                        //3.调用FileInputStream的方法,实现文件的读取
                        /*
                         * read():返回文件的一个字节,并指向下一个字节。当返回-1,文件读取结束
                         */
                        int b=fis.read();
                        while(b!=-1){
                            System.out.println((char)b);
                            b=fis.read();
                        }
                    } catch (FileNotFoundException e) {
                        // TODO 自动生成的 catch 块
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO 自动生成的 catch 块
                        e.printStackTrace();
                    }
                    finally{
                        //4.关闭相应的流
                        try {
                            fis.close();
                        } catch (IOException e) {
                            // TODO 自动生成的 catch 块
                            e.printStackTrace();
                        }
                    }
        }
        
        //抛出异常的方式
        @Test
        public void testFileInputStream1() throws IOException{
            //1.创建一个File类的对象
            File file=new File("hello.txt");
            //2.创建一个FileInputStream类的对象
            FileInputStream fis=new FileInputStream(file);
            //3.调用FileInputStream的方法,实现文件的读取
            /*
             * read():返回文件的一个字节,并指向下一个字节。当返回-1,文件读取结束
             */
            int b=fis.read();
            while(b!=-1){
                System.out.println((char)b);
                b=fis.read();
            }
            //4.关闭相应的流
            fis.close();
        }
    }
    FileInputOutputStream
    package com.btp.t4;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    
    import org.junit.Test;
    /*
     * 使用FileReader,FileWriter可以实现文本文件的复制
     * 对于非文本文件(视频文件,音频文件,图片等),只能使用字节流
     */
    public class TestFileReaderFileWriter {
        public static void main(String []args){
            //不能实现非文本文件的复制
            TestFileReaderFileWriter.copyTxt("hello1.txt", "hello2.txt");
        }
        
        
        //文本文件的读入
        @Test
        public void testFileReader(){
            File file1=new File("hello1.txt");
            
            FileReader frd=null;
            try {
                frd = new FileReader(file1);
            } catch (FileNotFoundException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            char[] c=new char[20];
            int len;
            try {
                while((len=frd.read(c))!=-1){
                    String str=new String(c,0,len);
                    System.out.print(str);
                }
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            try {
                frd.close();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
        //文本文件的复制
        public static void copyTxt(String str1,String str2){
            File file1=new File(str1);
            File file2=new File(str2);
            
            FileReader frd=null;
            try {
                frd = new FileReader(str1);
            } catch (FileNotFoundException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            FileWriter fwt=null;
            try {
                fwt = new FileWriter(str2);
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            
            char[] c=new char[20];
            int len;
            try {
                while((len=frd.read(c))!=-1){
                    try {
                        fwt.write(c,0,len);
                    } catch (IOException e) {
                        // TODO 自动生成的 catch 块
                        e.printStackTrace();
                    }
                }
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            try {
                frd.close();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
            try {
                fwt.close();
            } catch (IOException e) {
                // TODO 自动生成的 catch 块
                e.printStackTrace();
            }
        }
        
    }
    FileReaderWriter
      1 package com.btp.t4;
      2 
      3 import java.io.BufferedInputStream;
      4 import java.io.BufferedOutputStream;
      5 import java.io.BufferedReader;
      6 import java.io.BufferedWriter;
      7 import java.io.File;
      8 import java.io.FileInputStream;
      9 import java.io.FileNotFoundException;
     10 import java.io.FileOutputStream;
     11 import java.io.FileReader;
     12 import java.io.FileWriter;
     13 import java.io.IOException;
     14 
     15 import org.junit.Test;
     16 
     17 /*
     18  *IO的体系
     19  *抽象基类                                                               节点流(文件流)                缓冲流(处理流的一种,可以提升文件操作的效率)
     20  * InputStream(处理字节流)         FileInputStream              BufferedInputStream         
     21  * OutputStream(处理字节流)       FileOutputStream             BufferedOutputStream  (flush())
     22  * Reader(处理字符流)             FileReader(处理文本文件)      BufferedReader  (readLine())
     23  * Writer(处理字符流)             FileWriter(处理文本文件)      BufferedWriter  (flush())
     24  */
     25 public class TestBuffered {
     26     //使用BufferedInputStream和BufferedOutputStream实现非文本文件的复制
     27     @Test
     28     public void testBufferedInputOutputStream(){
     29         //1.提供读入,写出的文件
     30         File file1=new File("C:\Users\kobefan1\Desktop\adoub.jpg");
     31         File file2=new File("C:\Users\kobefan1\Desktop\adoub1.jpg");
     32         //2.创建相应的节点流:FileInputStream和FileOutputStream
     33         FileInputStream fis = null;
     34         try {
     35             fis = new FileInputStream(file1);
     36         } catch (FileNotFoundException e) {
     37             // TODO 自动生成的 catch 块
     38             e.printStackTrace();
     39         }
     40         FileOutputStream fos = null;
     41         try {
     42             fos = new FileOutputStream(file2);
     43         } catch (FileNotFoundException e) {
     44             // TODO 自动生成的 catch 块
     45             e.printStackTrace();
     46         }
     47         //3.将创建的节点流的对象作为形参传递给缓冲流的构造器中
     48         BufferedInputStream bis=new BufferedInputStream(fis);
     49         BufferedOutputStream bos=new BufferedOutputStream(fos);
     50         //4.具体的实现文件复制的操作
     51         byte[] b=new byte[20];
     52         int len;
     53         try {
     54             while((len=bis.read(b))!=-1){
     55                 bos.write(b,0,len);
     56                 bos.flush();//刷新一下
     57             }
     58         } catch (IOException e) {
     59             // TODO 自动生成的 catch 块
     60             e.printStackTrace();
     61         }
     62         //5.关闭相应的流
     63         try {
     64             bis.close();
     65         } catch (IOException e) {
     66             // TODO 自动生成的 catch 块
     67             e.printStackTrace();
     68         }
     69         try {
     70             bos.close();
     71         } catch (IOException e) {
     72             // TODO 自动生成的 catch 块
     73             e.printStackTrace();
     74         }
     75         
     76         
     77     }
     78     
     79     //使用BufferedReader和BufferedWriter实现文本文件的复制
     80     @Test
     81     public void testBufferedReaderWriter(){
     82         //1.提供读入,写出的文件
     83         File file1=new File("C:\Users\kobefan1\Desktop\hehe.txt");
     84         File file2=new File("C:\Users\kobefan1\Desktop\hehe1.txt");
     85         //2.创建相应的节点流:FileReader和FileWriter
     86         FileReader fis = null;
     87         try {
     88             fis = new FileReader(file1);
     89         } catch (FileNotFoundException e) {
     90             // TODO 自动生成的 catch 块
     91             e.printStackTrace();
     92         }
     93         FileWriter fos = null;
     94         try {
     95             fos = new FileWriter(file2);
     96         } catch (IOException e) {
     97             // TODO 自动生成的 catch 块
     98             e.printStackTrace();
     99         }
    100         //3.将创建的节点流的对象作为形参传递给缓冲流的构造器中
    101         BufferedReader bis=new BufferedReader(fis);
    102         BufferedWriter bos=new BufferedWriter(fos);
    103         //4.具体的实现文件复制的操作
    104         String str;
    105         try {
    106             while((str=bis.readLine())!=null){//每次读一行
    107                 bos.write(str);
    108                 bos.flush();
    109             }
    110         } catch (IOException e) {
    111             // TODO 自动生成的 catch 块
    112             e.printStackTrace();
    113         }
    114         //5.关闭相应的流
    115         try {
    116             bis.close();
    117         } catch (IOException e) {
    118             // TODO 自动生成的 catch 块
    119             e.printStackTrace();
    120         }
    121         try {
    122             bos.close();
    123         } catch (IOException e) {
    124             // TODO 自动生成的 catch 块
    125             e.printStackTrace();
    126         }
    127         
    128         
    129     }
    130 }
    Buffered
      1 package com.btp.t4;
      2 
      3 import java.io.BufferedInputStream;
      4 import java.io.BufferedOutputStream;
      5 import java.io.BufferedReader;
      6 import java.io.BufferedWriter;
      7 import java.io.File;
      8 import java.io.FileInputStream;
      9 import java.io.FileNotFoundException;
     10 import java.io.FileOutputStream;
     11 import java.io.FileReader;
     12 import java.io.FileWriter;
     13 import java.io.IOException;
     14 import java.io.Reader;
     15 
     16 import org.junit.Test;
     17 
     18 public class TestStreamandER {
     19   private String str="A BufferedInputStream adds functionality to another input stream-namely,
    "
     20            + " the ability to buffer the input and to support the mark and reset methods.
    "
     21            + " When the BufferedInputStream is created, an internal buffer array is created.
    "
     22            + " As bytes from the stream are read or skipped, the internal buffer is refilled as
    "
     23            + " necessary from the contained input stream, many bytes at a time. The mark operation 
    "
     24            + "remembers a point in the input stream and the reset operation causes all the bytes read 
    "
     25            + "since the most recent mark operation to be reread before new bytes are taken from the
    "
     26            + " contained input stream.";
     27    
     28    //使用字符流写出
     29    @Test
     30    public void testWriter()
     31    {
     32        BufferedWriter bfw = null;
     33     try {
     34         bfw = new BufferedWriter(new FileWriter(new File("java-Buffered.txt")));
     35     } catch (IOException e) {
     36         // TODO 自动生成的 catch 块
     37         e.printStackTrace();
     38     }
     39       
     40        try {
     41         bfw.write(str);
     42     } catch (IOException e) {
     43         // TODO 自动生成的 catch 块
     44         e.printStackTrace();
     45     }
     46        try {
     47         bfw.close();
     48     } catch (IOException e) {
     49         // TODO 自动生成的 catch 块
     50         e.printStackTrace();
     51     }
     52    }
     53    
     54  //使用字节流写出
     55    @Test
     56    public void testOutputStream()
     57    {
     58        BufferedOutputStream bfs = null;
     59     try {
     60         bfs = new BufferedOutputStream(new FileOutputStream(new File("Java-buffered-stream.txt")));
     61     } catch (FileNotFoundException e) {
     62         // TODO 自动生成的 catch 块
     63         e.printStackTrace();
     64     }
     65        try {
     66         bfs.write(str.getBytes());
     67     } catch (IOException e) {
     68         // TODO 自动生成的 catch 块
     69         e.printStackTrace();
     70     }
     71        try {
     72         bfs.close();
     73     } catch (IOException e) {
     74         // TODO 自动生成的 catch 块
     75         e.printStackTrace();
     76     }
     77    }
     78    
     79    //使用字节流读入
     80    @Test
     81    public void testInputStream(){
     82        BufferedInputStream bis = null;
     83     try {
     84         bis = new BufferedInputStream(new FileInputStream(new File("java-Buffered.txt")));
     85     } catch (FileNotFoundException e) {
     86         // TODO 自动生成的 catch 块
     87         e.printStackTrace();
     88     }
     89        byte[] b=new byte[1024];
     90        int len;
     91        try {
     92         while((len=bis.read(b))!=-1)
     93            {
     94                String str=new String(b,0,len);
     95                System.out.println(str);
     96            }
     97     } catch (IOException e) {
     98         // TODO 自动生成的 catch 块
     99         e.printStackTrace();
    100     }
    101        try {
    102         bis.close();
    103     } catch (IOException e) {
    104         // TODO 自动生成的 catch 块
    105         e.printStackTrace();
    106     }
    107        
    108    }
    109    
    110  //使用字符流读入
    111    @Test
    112    public void testReader(){
    113        BufferedReader br = null;
    114     try {
    115         br = new BufferedReader(new FileReader(new File("java-Buffered.txt")));
    116     } catch (FileNotFoundException e) {
    117         // TODO 自动生成的 catch 块
    118         e.printStackTrace();
    119     }
    120        char[] b=new char[1024];
    121        int len;
    122        try {
    123         while((len=br.read(b))!=-1)
    124            {
    125                String str=new String(b,0,len);
    126                System.out.println(str);
    127            }
    128     } catch (IOException e) {
    129         // TODO 自动生成的 catch 块
    130         e.printStackTrace();
    131     }
    132        try {
    133         br.close();
    134     } catch (IOException e) {
    135         // TODO 自动生成的 catch 块
    136         e.printStackTrace();
    137     }
    138        
    139    }
    140    
    141    //字节流实现复制
    142    @Test
    143    public void copyByte(){
    144        BufferedInputStream bis = null;
    145     try {
    146         bis = new BufferedInputStream(new FileInputStream(new File("java-Buffered.txt")));
    147     } catch (FileNotFoundException e) {
    148         // TODO 自动生成的 catch 块
    149         e.printStackTrace();
    150     }
    151        BufferedOutputStream bos = null;
    152     try {
    153         bos = new BufferedOutputStream(new FileOutputStream(new File("java-Buffered-copy.txt")));
    154     } catch (FileNotFoundException e) {
    155         // TODO 自动生成的 catch 块
    156         e.printStackTrace();
    157     }
    158        byte[] b=new byte[1024];
    159        int len;
    160        try {
    161         while((len=bis.read(b))!=-1){
    162                bos.write(b,0,len);
    163            }
    164     } catch (IOException e) {
    165         // TODO 自动生成的 catch 块
    166         e.printStackTrace();
    167     }
    168        try {
    169         bis.close();
    170     } catch (IOException e) {
    171         // TODO 自动生成的 catch 块
    172         e.printStackTrace();
    173     }
    174        try {
    175         bos.close();
    176     } catch (IOException e) {
    177         // TODO 自动生成的 catch 块
    178         e.printStackTrace();
    179     }
    180    }
    181    
    182    
    183    
    184  //字符流实现复制
    185    @Test
    186    public void copyChar(){
    187        BufferedReader bis = null;
    188     try {
    189         bis = new BufferedReader(new FileReader(new File("java-Buffered.txt")));
    190     } catch (FileNotFoundException e) {
    191         // TODO 自动生成的 catch 块
    192         e.printStackTrace();
    193     }
    194        BufferedWriter bos = null;
    195     try {
    196         bos = new BufferedWriter(new FileWriter(new File("java-Buffered-copy2.txt")));
    197     } catch (IOException e) {
    198         // TODO 自动生成的 catch 块
    199         e.printStackTrace();
    200     }
    201        char[] b=new char[1024];
    202        int len;
    203        try {
    204         while((len=bis.read(b))!=-1){
    205                bos.write(b,0,len);
    206            }
    207     } catch (IOException e) {
    208         // TODO 自动生成的 catch 块
    209         e.printStackTrace();
    210     }
    211        try {
    212         bis.close();
    213     } catch (IOException e) {
    214         // TODO 自动生成的 catch 块
    215         e.printStackTrace();
    216     }
    217        try {
    218         bos.close();
    219     } catch (IOException e) {
    220         // TODO 自动生成的 catch 块
    221         e.printStackTrace();
    222     }
    223    }
    224 }
    Practice
      1 package com.btp.t4;
      2 
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.FileOutputStream;
      6 import java.io.IOException;
      7 import java.io.ObjectInputStream;
      8 import java.io.ObjectOutputStream;
      9 import java.io.Serializable;
     10 
     11 import org.junit.Test;
     12 
     13 public class TestObjectInputOutputStream {
     14     //对象的序列化过程:将内存中的对象通过ObjectOutputStream转换为二进制流,存储在硬盘文件中
     15     @Test
     16     public void testObjectOutputStream(){
     17         Persons p1=new Persons("超人",10000,new Pet("花花"));
     18         Persons p2=new Persons("蜘蛛侠",20,new Pet("章鱼"));
     19         ObjectOutputStream oos = null;
     20         try {
     21             oos = new ObjectOutputStream(new FileOutputStream(new File("chaoren.txt")));
     22             oos.writeObject(p1);
     23             oos.flush();
     24             oos.writeObject(p2);
     25             oos.flush();
     26         } catch (IOException e) {
     27             // TODO 自动生成的 catch 块
     28             e.printStackTrace();
     29         }finally{
     30         try {
     31             oos.close();
     32         } catch (IOException e) {
     33             // TODO 自动生成的 catch 块
     34             e.printStackTrace();
     35         }
     36         }
     37     }
     38     
     39     //对象的反序列化过程:将硬盘中的文件通过ObjectInputStream转换为相应的对象
     40     @Test
     41     public void testObjectInputStream(){
     42         ObjectInputStream ois = null;
     43         try {
     44             ois = new ObjectInputStream(new FileInputStream(new File("chaoren.txt")));
     45             Persons p1=(Persons) ois.readObject();
     46             Persons p2=(Persons) ois.readObject();
     47             System.out.println(p1);
     48             System.out.println(p2);
     49         } catch (ClassNotFoundException | IOException e) {
     50             // TODO 自动生成的 catch 块
     51             e.printStackTrace();
     52         }
     53         finally{
     54         try {
     55             ois.close();
     56         } catch (IOException e) {
     57             // TODO 自动生成的 catch 块
     58             e.printStackTrace();
     59         }
     60         }
     61     }
     62 }
     63 
     64 
     65 //
     66 /*
     67  * 要实现序列化的类:
     68  * 1.要求此类是可序列化的,必须实现Serializable接口
     69  * 2.要求类的属性同样要实现Serializable接口
     70  * 3.提供一个版本号,private static final long serialVersionUID
     71  * 4.不能序列化static和transient修饰的成员属性
     72  */
     73 class Persons implements Serializable{
     74     private static final long serialVersionUID=546541684;//用来表明类的不同版本间的兼容性
     75     String name;//static String name;
     76     Integer age;//transient Integer age;
     77     Pet pet;
     78     public Persons(String name,Integer age,Pet pet){
     79         this.name=name;
     80         this.age=age;
     81         this.pet=pet;
     82     }
     83     public Persons() {
     84         super();
     85     }
     86     @Override
     87     public String toString() {
     88         return "Persons [name=" + name + ", age=" + age + ", pet=" + pet + "]";
     89     }
     90     
     91 }
     92 
     93 class Pet implements Serializable{
     94     String name;
     95 
     96     public Pet(String name) {
     97         super();
     98         this.name = name;
     99     }
    100 
    101     public Pet() {
    102         super();
    103         // TODO 自动生成的构造函数存根
    104     }
    105 
    106     @Override
    107     public String toString() {
    108         return "Pet [name=" + name + "]";
    109     }
    110     
    111 }
    ObjectInputOutputStream
      1 package com.btp.t4;
      2 
      3 import java.io.File;
      4 import java.io.IOException;
      5 import java.io.RandomAccessFile;
      6 
      7 import org.junit.Test;
      8 
      9 /*
     10  * RandomAccessFile:支持随机访问
     11  * 1.即可以充当一个输入流,又可以充当一个输出流
     12  * 2.支持从文件的开头读取,写入
     13  * 3.支持从任意位置的读取,写入(插入)
     14  */
     15 public class TestRandomAccessFile {
     16     //进行文件的读,写
     17     @Test
     18     public void test1(){
     19         RandomAccessFile raf1 = null;
     20         RandomAccessFile raf2 = null;
     21         try {
     22             raf1 = new RandomAccessFile(new File("hello1.txt"), "r");
     23             raf2 = new RandomAccessFile(new File("RandomAccess.txt"), "rw");
     24             
     25             byte[] b=new byte[1024];
     26             int len;
     27             while((len=raf1.read(b))!=-1){
     28                 raf2.write(b, 0, len);
     29             }
     30         } catch (IOException e) {
     31             // TODO 自动生成的 catch 块
     32             e.printStackTrace();
     33         }
     34         
     35         try {
     36             raf1.close();
     37         } catch (IOException e) {
     38             // TODO 自动生成的 catch 块
     39             e.printStackTrace();
     40         }
     41         try {
     42             raf2.close();
     43         } catch (IOException e) {
     44             // TODO 自动生成的 catch 块
     45             e.printStackTrace();
     46         }
     47     }
     48     //实现的实际上是覆盖的效果
     49     @Test
     50     public void test2(){
     51         RandomAccessFile raf2 = null;
     52         try {
     53             raf2 = new RandomAccessFile(new File("RandomAccess.txt"), "rw");
     54             raf2.seek(0);//在0的位置写入
     55             raf2.write(new String("Man in black!").getBytes());
     56         } catch (IOException e) {
     57             // TODO 自动生成的 catch 块
     58             e.printStackTrace();
     59         }
     60         try {
     61             raf2.close();
     62         } catch (IOException e) {
     63             // TODO 自动生成的 catch 块
     64             e.printStackTrace();
     65         }
     66     }
     67     
     68     //实现插入的效果(文件只有一行)
     69     @Test
     70     public void test3(){
     71         RandomAccessFile raf2 = null;
     72         try {
     73             raf2 = new RandomAccessFile(new File("RandomAccess.txt"), "rw");
     74             raf2.seek(0);//在0的位置写入
     75             String str=raf2.readLine();//把插入位置的后面的内容读出来
     76             
     77             System.out.println(raf2.getFilePointer());
     78             raf2.seek(0);//指针再调回要插入的位置
     79             raf2.write(new String("hehe!!").getBytes());//插入
     80             raf2.write(str.getBytes());//在插入 内容后还原原来后面的内容
     81         } catch (IOException e) {
     82             // TODO 自动生成的 catch 块
     83             e.printStackTrace();
     84         }
     85         try {
     86             raf2.close();
     87         } catch (IOException e) {
     88             // TODO 自动生成的 catch 块
     89             e.printStackTrace();
     90         }
     91     }
     92     
     93     //实现插入的效果(文件有多行,比较复杂的文件)
     94         @Test
     95         public void test4(){
     96             RandomAccessFile raf2 = null;
     97             try {
     98                 raf2 = new RandomAccessFile(new File("RandomAccess.txt"), "rw");
     99                 raf2.seek(0);
    100                 byte[] b=new byte[20];
    101                 int len;
    102                 StringBuffer sb=new StringBuffer();
    103                 while((len=raf2.read(b))!=-1){
    104                     sb.append(new String(b,0,len));//每一次字符串都会加长
    105                 }
    106                 raf2.seek(0);
    107                 raf2.write(new String("Kobe!!!!").getBytes());
    108                 raf2.write(sb.toString().getBytes());
    109                 
    110             } catch (IOException e) {
    111                 // TODO 自动生成的 catch 块
    112                 e.printStackTrace();
    113             }
    114             try {
    115                 raf2.close();
    116             } catch (IOException e) {
    117                 // TODO 自动生成的 catch 块
    118                 e.printStackTrace();
    119             }
    120         }
    121 }
    RandomAccessFile
      1 package com.btp.t4;
      2 
      3 import java.io.BufferedReader;
      4 import java.io.BufferedWriter;
      5 import java.io.DataInputStream;
      6 import java.io.DataOutputStream;
      7 import java.io.File;
      8 import java.io.FileInputStream;
      9 import java.io.FileNotFoundException;
     10 import java.io.FileOutputStream;
     11 import java.io.IOException;
     12 import java.io.InputStream;
     13 import java.io.InputStreamReader;
     14 import java.io.OutputStreamWriter;
     15 import java.io.UnsupportedEncodingException;
     16 
     17 import org.junit.Test;
     18 
     19 public class TestOtherStream {
     20     /*
     21      * 如何实现字节流和字符流之间的转换
     22      * 转换流:InputStreamReader  OutputStreamWriter
     23      * 编码:字符串--->字节数组
     24      * 解码:字节数组--->字符串
     25      */
     26     @Test
     27     public void test1(){
     28         //解码
     29         File file=new File("hello1.txt");
     30         FileInputStream fis = null;
     31         try {
     32             fis = new FileInputStream(file);
     33         } catch (FileNotFoundException e1) {
     34             // TODO 自动生成的 catch 块
     35             e1.printStackTrace();
     36         }
     37         InputStreamReader isr = null;
     38         try {
     39             isr = new InputStreamReader(fis,"GBK");
     40         } catch (UnsupportedEncodingException e) {
     41             // TODO 自动生成的 catch 块
     42             e.printStackTrace();
     43         }
     44         BufferedReader br=new BufferedReader(isr);
     45         //编码
     46         File file1=new File("hello15.txt");
     47         FileOutputStream fos = null;
     48         try {
     49             fos = new FileOutputStream(file1);
     50         } catch (FileNotFoundException e) {
     51             // TODO 自动生成的 catch 块
     52             e.printStackTrace();
     53         }
     54         OutputStreamWriter osw = null;
     55         try {
     56             osw = new OutputStreamWriter(fos,"GBK");
     57         } catch (UnsupportedEncodingException e) {
     58             // TODO 自动生成的 catch 块
     59             e.printStackTrace();
     60         }
     61         BufferedWriter bw=new BufferedWriter(osw);
     62         String str;
     63         try {
     64             while((str=br.readLine())!=null){
     65                 bw.write(str);
     66                 bw.newLine();
     67                 bw.flush();
     68             }
     69         } catch (IOException e) {
     70             // TODO 自动生成的 catch 块
     71             e.printStackTrace();
     72         }
     73         try {
     74             fis.close();
     75         } catch (IOException e) {
     76             // TODO 自动生成的 catch 块
     77             e.printStackTrace();
     78         }
     79         try {
     80             isr.close();
     81         } catch (IOException e) {
     82             // TODO 自动生成的 catch 块
     83             e.printStackTrace();
     84         }
     85         try {
     86             fos.close();
     87         } catch (IOException e) {
     88             // TODO 自动生成的 catch 块
     89             e.printStackTrace();
     90         }
     91         try {
     92             osw.close();
     93         } catch (IOException e) {
     94             // TODO 自动生成的 catch 块
     95             e.printStackTrace();
     96         }
     97         try {
     98             br.close();
     99         } catch (IOException e) {
    100             // TODO 自动生成的 catch 块
    101             e.printStackTrace();
    102         }
    103         try {
    104             bw.close();
    105         } catch (IOException e) {
    106             // TODO 自动生成的 catch 块
    107             e.printStackTrace();
    108         }
    109     }
    110     
    111     
    112     /*
    113      * 标准的输入输出流:
    114      * 标准的输入流:System.in
    115      * 标准的输出流:System.out
    116      */
    117     @Test
    118     public void test2()
    119     {
    120         InputStream is=System.in;//字节流输入
    121         InputStreamReader isr=new InputStreamReader(is);//转换为字符流
    122         BufferedReader br=new BufferedReader(isr);//变为带缓冲的字符流
    123         
    124         String str = null;
    125         while(true){
    126             System.out.println("请输入字符串:");
    127             try {
    128                 str=br.readLine();
    129             } catch (IOException e) {
    130                 // TODO 自动生成的 catch 块
    131                 e.printStackTrace();
    132             }
    133             if(str.equalsIgnoreCase("e")||str.equalsIgnoreCase("exit")){
    134                 break;
    135             }
    136             String str1=str.toUpperCase();
    137             System.out.println(str1);
    138         }
    139         try {
    140             br.close();
    141         } catch (IOException e) {
    142             // TODO 自动生成的 catch 块
    143             e.printStackTrace();
    144         }
    145     }
    146     
    147     
    148     /*
    149      * 打印流:    字节流:PrintStream,字符流:PrintWriter
    150      */
    151     @Test
    152     public void test3(){
    153         
    154     }
    155     
    156     /*
    157      * 数据流:    DataInputStream,DataOutputStream
    158      */
    159     @Test
    160     public void test4(){
    161         DataOutputStream dos = null;
    162         try {
    163             dos = new DataOutputStream(new FileOutputStream(new File("data.txt")));
    164             dos.writeInt(123);
    165             dos.writeUTF("我喜欢Java");
    166             dos.writeLong(157571959);
    167             dos.writeBoolean(false);
    168         } catch (IOException e) {
    169             // TODO 自动生成的 catch 块
    170             e.printStackTrace();
    171         }
    172         finally{
    173         try {
    174             dos.close();
    175         } catch (IOException e) {
    176             // TODO 自动生成的 catch 块
    177             e.printStackTrace();
    178         }
    179         }
    180         
    181         DataInputStream dis=null;
    182         try {
    183             dis = new DataInputStream(new FileInputStream(new File("data.txt")));
    184             System.out.println(dis.readInt());
    185             System.out.println(dis.readUTF());
    186             System.out.println(dis.readLong());
    187             System.out.println(dis.readBoolean());
    188         } catch (IOException e) {
    189             // TODO 自动生成的 catch 块
    190             e.printStackTrace();
    191         }
    192         try {
    193             dis.close();
    194         } catch (IOException e) {
    195             // TODO 自动生成的 catch 块
    196             e.printStackTrace();
    197         }
    198     }
    199     
    200 }
    OtherStream
     1 package com.btp.t4;
     2 
     3 import java.io.BufferedReader;
     4 import java.io.IOException;
     5 import java.io.InputStreamReader;
     6 
     7 public class MyInput {
     8     public String nextString(){
     9         InputStreamReader isr=new InputStreamReader(System.in);
    10         BufferedReader br=new BufferedReader(isr);
    11         String str = null;
    12         try {
    13             str = br.readLine();
    14         } catch (IOException e) {
    15             // TODO 自动生成的 catch 块
    16             e.printStackTrace();
    17         }
    18         return str;
    19         
    20     }
    21     
    22     public int nextInt(){
    23         return Integer.parseInt(nextString());
    24     }
    25     
    26     public boolean nextBoolean(){
    27         return Boolean.parseBoolean(nextString());
    28     }
    29     
    30     public static void main(String[] args){
    31         MyInput i=new MyInput();
    32         System.out.println("请输入一个字符串:");
    33         String str=i.nextString();
    34         System.out.println(str);
    35         
    36         int j=i.nextInt();
    37         System.out.println(j+1);
    38     }
    39     
    40 }
    MyInput
  • 相关阅读:
    委托学习小记(1)
    C# 对XML的 创建、查询
    C#多线程学习(六) 互斥对象
    C#多线程学习(二) 如何操纵一个线程
    C#多线程学习(四) 多线程的自动管理(线程池)
    16/11/22_plsql
    写日志
    内存检测
    开源
    vs2005 远程调试。
  • 原文地址:https://www.cnblogs.com/a842297171/p/5176861.html
Copyright © 2020-2023  润新知