首页 > 代码库 > IO学习小结

IO学习小结

一、文件操作

1、File类:对文件的外部操作

2、RandomAccessFile类:对文件的内容操作

代码演练1:

       要求:1、创建目录A,A下有目录B和C,B中有目录D和文件b.txt,D中有文件d.txt,C中有文件c.jpg

               2、遍历A中所有文件和目录

               3、遍历A中jpg格式的文件

               4、删除A中所有内容包括A

package BlogCode;
import java.io.*;
public class 代码演练1 {
    private static Object file;
    public static void main(String[] args) {
        /**
         * "."表示当前目录
         * ".."表示上一目录
         * File.separator 表示分隔符
         * 
         */
        File dir = new File("."+File.separator+"A");
        if(!dir.exists()){
            dir.mkdir();
        }
        File dir1 = new File("."+File.separator+"A"+"."+File.separator+"B"+"."+File.separator+"D");
        if(!dir1.exists()){
            dir1.mkdirs();
        }
        File dir2 = new File("."+File.separator+"A"+"."+File.separator+"C");
        if(!dir2.exists()){
            dir2.mkdirs();
        }
        File b = new File("."+File.separator+"A"+"."+File.separator+"B"+"."+File.separator+"b.txt");
        if(!b.exists()){
            try {
                b.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        File c = new File("."+File.separator+"A"+"."+File.separator+"C"+"."+File.separator+"c.jpg");
        if(!c.exists()){
            try {
                c.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        File d = new File("."+File.separator+"A"+"."+File.separator+"B"+"."+File.separator+"D"+"."+File.separator+"d.txt");
        if(!d.exists()){
            try {
                d.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        findAllFile(dir);
        findjpg(dir);
        deleteAll(dir);    
    }
    private static void findjpg(File dir) {
//        FileFilter ff = new FileFilter() {
//            public boolean accept(File pathname) {
//                return pathname.getName().endsWith(".jpg");
//            }
//        };
        File[] subs = dir.listFiles();
        for(File sub:subs){
            if(sub.isFile()&&sub.getName().endsWith(".jpg")){
                System.out.println("文件.jpg:"+sub.getName());
            }else if(sub.isDirectory()){
                findjpg(sub);
            }
        }
    }
    private static void findAllFile(File dir) {
        File[] subs = dir.listFiles();
        for(File sub:subs){
            if(sub.isFile()){
                System.out.println("文件:"+sub.getName());
            }else{
                findAllFile(sub);
                System.out.println("目录:"+sub.getName());
            }
        }    
    }
    private static void deleteAll(File dir) {
        File[] subs = dir.listFiles();
        for(File sub:subs){
            if(sub.isFile()){
                sub.delete();
            }else{
                deleteAll(sub);
                sub.delete();
            }
        }
        dir.delete();
    }
}

代码演练2:

       要求:1、创建一个demo.txt文件并输入“你好,java!”,将全部内容复制到demo1_copy.txt中,输出“av”并将其复制到demo2_copy.txt中

 

package BlogCode;

import java.io.*;

public class 代码演练2 {
    public static void main(String[] args) throws IOException {
        /**
         * RandomAccessFile   用指针操作
         */
        RandomAccessFile raf = new RandomAccessFile("demo.txt", "rw");
        RandomAccessFile raf1 = new RandomAccessFile("demo1_copy1.txt", "rw");
        RandomAccessFile raf2 = new RandomAccessFile("demo1_copy2.txt", "rw");
        raf.write("你好,java!".getBytes());
        long getPointerindex = raf.getFilePointer();
        System.out.println(getPointerindex);
        raf.seek(0);
        int r =-1; 
        while((r=raf.read())!=-1){
            raf1.write(r);
        }
        raf.seek(0);
        byte[] by = new byte[20];
        while(raf.read(by)!=-1){
            raf2.write(by);
            System.out.println(new String(by,7,2,"GBK"));
        }
        raf1.close();
        raf2.close();
    }
}

 二、IO流

2.1.字节流:InputStream      是所有字节输入流的父类          

                OutputStream    是所有字节输出流的父类  

                2.1.1.文件流(低级流):FileInputStream   文件输入流-----------FIS

                                   FileOutputStream 文件输出流-----------FOS

                2.1.2.缓冲流:BufferedInputStream   缓冲输入流---------BIS

                                   BufferedOutputStream 缓冲输出流---------BOS

                2.1.3.对象流:ObjectInputStream  对象输入流-----------OIS

                                    ObjectOutputStream  对象输出流-----------OOS

2.2.字符流:Reader  是所有字符输入流的父类

                Writer   是所有字符输出流的父类

                2.2.1.转换流:InputStreamReader  字符输入流----------ISR

                                   OutputStreamWriter  字符输出流---------OSW

                2.2.2缓冲字符流:BufferedReader  缓冲字符输入流--------BR

                                        PrintWriter       缓冲字符输出流----------PW

代码演练3:

       要求:1.用字节流将"旋转的卡特琳娜"写入文件lol.txt中,并将"卡特"输出

              2.用缓冲流将"旋转的德玛西亚之力"写入文件lol1.txt中,并将文件内容复制到lol2.txt

package BlogCode;
import java.io.*;
public class 代码演练3 {
    public static void main(String[] args) throws Exception {
        FileOutputStream fos =  new FileOutputStream("lol.txt");
        fos.write("旋转的卡特琳娜".getBytes());
        FileInputStream fis = new FileInputStream("lol.txt");
        byte[] by1 = new byte[15];
        fis.read(by1);
        System.out.println(new String(by1,6,4));
        fos.close();
        fis.close();
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("lol1.txt"));
        bos.write("旋转的德玛西亚之力".getBytes());
        bos.flush();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("lol1.txt"));
        BufferedOutputStream bos1 = new BufferedOutputStream(new FileOutputStream("lol2.txt"));
        int r=-1;
        while((r=bis.read())!=-1){
            bos1.write(r);
        }
        bos1.close();
        bos.close();
        bis.close();
    }
}

 代码演练4:

        要求:1.建立一个Person类,在测试类中创建一个Person对象,并将其序列化和反序列化

                2.在测试类中创建一个Person对象数组,并将其序列化和反序列化

package BlogCode;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class 代码演练4 {
    /**
     * 注意要序列化的类必须实现Serializable接口,并要定义序列版本号serialVersionUID
     */
    public static void main(String[] args) throws Exception {
        Person p = new Person("miss",26);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("pp.obj"));
        oos.writeObject(p);
        oos.close();
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("pp.obj"));
        Person p0 = (Person) ois.readObject();
        System.out.println(p0);
        ois.close();
        System.out.println("--------------------");
        Person p1 = new Person("熊大",12);
        Person p2 = new Person("熊二",13);
        Person p3 = new Person("光头强",30);
        Set<Person> s = new HashSet<Person>();
        s.add(p1);
        s.add(p2);
        s.add(p3);
        ObjectOutputStream oos1 = new ObjectOutputStream(new FileOutputStream("pp1.obj"));
        oos1.writeObject(s);
        oos1.close();
        ObjectInputStream ois1 = new ObjectInputStream(new FileInputStream("pp1.obj"));
        Set<Person> set = (Set)ois1.readObject();
        for(Person o:set){
            System.out.println(o);
        }
        ois1.close();
    }
}
class Person implements Serializable{
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    public Person() {
        super();
    }
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }    
}

 代码演练5:

        要求:用字符流将"我只有飞速的旋转,才能止住我的泪水,忘记你的模样"输入文件demo5.txt,并将内容输出

package BlogCode;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class 代码演练5 {
    public static void main(String[] args) throws Exception, FileNotFoundException {
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("demo5.txt"), "GBK");
        osw.write("我只有飞速的旋转,才能止住我的泪水,忘记你的模样");
        osw.close();
        InputStreamReader isr = new InputStreamReader(new FileInputStream("demo5.txt"),"GBK");
        int r =-1;
        while((r=isr.read())!=-1){
            System.out.print((char)r);
        }
        isr.close();
    }
}

代码演练6:

       要求:用缓冲字符流将"平生不修善果,最爱杀人放火。

                                     忽地顿开金绳,这里扯断玉锁。

                                     咦,钱塘江上潮信来,今日方知我是我!

                                                        --------------花和尚:鲁智深"

package BlogCode;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class 代码演练6 {
    public static void main(String[] args) throws Exception {
        FileOutputStream fos = new FileOutputStream("demo06.txt");
        OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
        PrintWriter pw = new PrintWriter(osw,true);
        pw.println("平生不修善果,最爱杀人放火。");
        pw.println("忽地顿开金绳,这里扯断玉锁。");
        pw.println("咦,钱塘江上潮信来,今日方知我是我!");
        pw.println("                              ------------------花和尚:鲁智深");
        pw.flush();
        pw.close();
        FileInputStream fis = new FileInputStream("demo06.txt");
        InputStreamReader isr = new InputStreamReader(fis,"GBK");
        BufferedReader br = new BufferedReader(isr);
        String s = null;
        while((s=br.readLine())!=null){
            System.out.println(s);
        }
    }
}

IO学习小结