IO操作

1、File的简单操作

public class IOTest01 {
    public static void main(String[] args) {
        String path = "D:/temp/";
//      File temp =File.createTempFile("asa", ".temp", new File(path));创建临时文件
//      temp.deleteOnExit();删除临时文件
        testFile01(path);
    }
    
    public static void testFile01(String path){
        if(path!=null){
            File file = new File(path);
            if(file.isDirectory()){//判断是否是文件夹
                System.out.println(path+"是文件夹");
                //File[] roots = File.listRoots();//获取盘符所有目录[C:\, D:\, E:\, F:\, H:\]
                //System.out.println(Arrays.toString(roots));
                String[] files = file.list();//获取文件夹下面所有文件名,包括文件夹的名称
                System.out.println(Arrays.toString(files));
                testFile02(file,"");
                
            }else if(file.isFile()){//判断是否是文件
                System.out.println(path+"是文件");
                System.out.println(file.getName()+"能否可写:"+file.canWrite());
                System.out.println(file.getName()+"能否可读:"+file.canRead());
                System.out.println(file.getName()+"长度:"+file.length());
                //file.renameTo(new File())删掉原来的文件,并把文件创建、复制到新的文件
                System.out.println(file.getName()+"改名:"+file.renameTo(new File("D:/temp/a/newName.txt")));
                //file.delete();删除文件
            }else{
                System.out.println(path+"不存在");
                boolean flag = file.mkdir();//创建文件夹,必须保证父目录存在,否则创建不成功
                System.out.println(flag?"创建成功":"创建失败");
                if(!flag)file.mkdirs();//创建文件夹,如果整个文件夹链上有不存在的,则都会创建
            }
        }
    }
    
    public static void testFile02(File file,String kg){
        File[] files2 = file.listFiles();
//      File[] files2 = file.listFiles(new FilenameFilter(){
//          public boolean accept(File dir, String name) {//此处dir和name代表遍历出的文件目录和文件名
//              return new File(dir,name).isFile() && name.lastIndexOf(".txt")>0;
//          }});listFiles(new FilenameFilter(){});此方法用来过滤文件
        if(kg==null || kg.equals("")){kg = "|----";}else{kg=kg.replace("|", " ");kg=kg.replace("-", " ");kg = kg+"|----";}
        for(File f : files2){
            if(f.isDirectory()){//如果是文件夹
                System.out.println(kg+f.getName());
                testFile02(f,kg);
            }else{
                System.out.println(kg+f.getName());
            }
        }
    }
}

2、节点流与功能流
2.1、节点流
字节流:InputStream、OutputStream、FileInputStream、FileOutputStream
字符流:Writer、Reader、FileWriter、FileReader
字节流:InputStream、OutputStream、FileInputStream、FileOutputStream

public class IOTest02 {
    public static void main(String[] args) {
        String path1 = "D:/temp/";
        String path2 = "D:/temp2/";
        //inputStreamTest(path1);
        //outputStreamTest(path2);
        //copyFile(path1,path2);
        copyDir(path1,path2);
    }
    public static void inputStreamTest(String path){
        File file = new File(path);
        InputStream ins =null;
        try {
            ins = new FileInputStream(file);
            byte[] b = new byte[512];
            int len = 0;
            while(-1!=(len = ins.read(b))){
                System.out.println(new String(b,"GBK"));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(ins!=null){try {ins.close();} catch (IOException e) {e.printStackTrace();}}
        }
    }
    public static void outputStreamTest(String path){
        File file = new File(path);
        OutputStream outs =null;
        try {
            outs = new FileOutputStream(file);
            String value = "safsag阿萨德刚三个色";
            outs.write(value.getBytes());
            outs.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(outs!=null){try {outs.close();} catch (IOException e) {e.printStackTrace();}}
        }
    }
    public static void copyFile(String srcPath,String destPath){
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);
        copyFile(srcFile,destFile);
    }
    public static void copyFile(File srcFile,File destFile){//拷贝文件
        InputStream ins = null;
        OutputStream outs =null;
        try {
            ins = new FileInputStream(srcFile);
            outs = new FileOutputStream(destFile);//默认是不追加的,若为new FileOutputStream(destFile,true),则为追加
            byte[] b = new byte[512];
            int len = 0;
            while(-1!=(len=ins.read(b))){
                outs.write(b, 0, len);
            }
            outs.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(ins!=null){try {ins.close();} catch (IOException e) {e.printStackTrace();}}
            if(outs!=null){try {outs.close();} catch (IOException e) {e.printStackTrace();}}
        }
    }
    
    public static void copyDir(String srcPath,String destPath){//拷贝文件夹及其内容
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);
        if(!srcFile.isDirectory()){
            System.out.println("原地址不是正确的文件夹地址");
            return;
        }else if(!destFile.isDirectory()){
            destFile.mkdirs();
        }
        File destRoot = new File(destPath,srcFile.getName());
        destRoot.mkdir();
        copyDirHelper(srcFile,destRoot);
        File[] files = srcFile.listFiles();
    }
    
    public static void copyDirHelper(File srcFile,File destFile){
        File[] files = srcFile.listFiles();
        for(File file:files){
            if(file.isDirectory()){
                (new File(destFile.getAbsolutePath(),file.getName())).mkdir();
                copyDirHelper(file,new File(destFile.getAbsolutePath(),file.getName()));
            }else if(file.isFile()){
                copyFile(file,new File(destFile.getAbsolutePath(),file.getName()));
            }
        }
    }
}

2.2、字符流Writer、Reader、FileWriter、FileReader

public class IOTest03 {
    public static void main(String[] args) {
        String path1 ="D:/temp/caililiang2.txt";
        String path2 ="D:/temp/caililiang5.txt";
        //readerTest(path1);
        //writerTest(path2);
        copyFile(path1,path2);
    }
    public static void readerTest(String path){
        File file = new File(path);
        Reader read =null;
        try {
            read = new FileReader(file);
            char[] c = new char[512];
            int len =0;
            while(-1!=(len = read.read(c))){
                System.out.println(new String(c));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(read!=null){try {read.close();} catch (IOException e) {e.printStackTrace();}}
        }
    }
    
    public static void writerTest(String path){
        File file = new File(path);
        Writer writer =null;
        try {
            writer = new FileWriter(file);
            String value = "safsdgdsfgsdfgsd";
            writer.write(value);
            writer.append("=====sdsdgdsf");
            writer.flush();
        } catch (Exception e) {
        } finally{
            if(writer!=null){try {writer.close();} catch (IOException e) {e.printStackTrace();}}
        }
    }
    public static void copyFile(String srcpath,String destpath){//拷贝文件
        File srcFile = new File(srcpath);
        File destFile = new File(destpath);
        copyFile(srcFile,destFile);
    }
    
    public static void copyFile(File srcFile,File destFile){//拷贝文件
        Reader read =null;
        Writer writer =null;
        try {
            read = new FileReader(srcFile);
            writer = new FileWriter(destFile);
            int len = 0;
            char[] c = new char[512];
            while(-1!=(len = read.read(c))){
                writer.write(c,0,len);
            }
            writer.flush();
        } catch (Exception e) {
            
        } finally{
            if(read!=null){try {read.close();} catch (IOException e) {e.printStackTrace();}}
            if(writer!=null){try {writer.close();} catch (IOException e) {e.printStackTrace();}}
        }
    }
}

2.3、字节缓冲流(BufferedInputStream、BufferedOutputStream)与字符缓冲流(BufferedReader、BufferedWriter)

public static void main(String[] args) {
        File srcFile = new File("D:/temp/caililiang2.txt");
        File destFile = new File("D:/temp/caililiang5.txt");
        //copyFile(srcFile,destFile);
        copyFile2(srcFile,destFile);
    }
    
    public static void copyFile(File srcFile,File destFile){//拷贝文件
        InputStream ins = null;
        OutputStream outs =null;
        try {
            //字节缓冲流:加快流操作速度
            //new BufferedInputStream(new InputStream(new File(""))),
            //new BufferedOutputStream(new OutputStream(new File("")))
            ins = new BufferedInputStream(new FileInputStream(srcFile));
            outs = new BufferedOutputStream(new FileOutputStream(destFile));//默认是不追加的,若为new FileOutputStream(destFile,true),则为追加
            byte[] b = new byte[512];
            int len = 0;
            while(-1!=(len=ins.read(b))){
                outs.write(b, 0, len);
            }
            outs.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(ins!=null){try {ins.close();} catch (IOException e) {e.printStackTrace();}}
            if(outs!=null){try {outs.close();} catch (IOException e) {e.printStackTrace();}}
        }
    }
    
    public static void copyFile2(File srcFile,File destFile){//拷贝文件
        BufferedReader read =null;
        BufferedWriter writer =null;
        try {
            //字符缓冲流:提供了新方法BufferedReader.readLine()读取一行,BufferedWriter.newLine()换行
            //new BufferedReader(new FileReader(srcFile)),new BufferedWriter(new FileWriter(destFile))
            read = new BufferedReader(new FileReader(srcFile));
            writer = new BufferedWriter(new FileWriter(destFile));
            String line = null;
            while(null!=(line=read.readLine())){
                writer.write(line);
                writer.newLine();//等同writer.append("\r\n");
            }
            writer.flush();
        } catch (Exception e) {
            
        } finally{
            if(read!=null){try {read.close();} catch (IOException e) {e.printStackTrace();}}
            if(writer!=null){try {writer.close();} catch (IOException e) {e.printStackTrace();}}
        }
    }
}

2.4、转换流(InputStreamReader,OutputStreamWriter)
转换流InputStreamReader(InputStream,String)把字节输入流转换到字符输入流
转换流OutputStreamWriter(InputStream,String)把字节输出流转换到字符输出流

public class IOTest05 {
    public static void main(String[] args) {
        File srcFile = new File("D:/temp/caililiang2.txt");
        File destFile = new File("D:/temp/caililiang5.txt");
        copyFile(srcFile,destFile);
    }
    public static void copyFile(File srcFile,File destFile){//拷贝文件
        BufferedReader read =null;
        BufferedWriter writer =null;
        try {
            //转换流InputStreamReader(InputStream,String)把字节输入流转换到字符输入流
            //转换流OutputStreamWriter(InputStream,String)把字节输出流转换到字符输出流
            read = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile),"GB2312"));
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile),"GB2312"));
            String line = null;
            while(null!=(line=read.readLine())){
                writer.write(line);
                writer.newLine();//等同writer.append("\r\n");
            }
            writer.flush();
        } catch (Exception e) {
            
        } finally{
            if(read!=null){try {read.close();} catch (IOException e) {e.printStackTrace();}}
            if(writer!=null){try {writer.close();} catch (IOException e) {e.printStackTrace();}}
        }
    }
}

2.5、字节数组流(ByteArrayInputStream、ByteArrayOutputStream)

public class IOTest06 {
    public static void main(String[] args) {
        File srcFile = new File("D:/temp/178_IO_重点流_总结.mp4");
        File destFile = new File("D:/temp/178_IO.mp4");
        try {
            byte[] datas = fileToBytes(srcFile);
            System.out.println(datas.length);
            BytesTofile(datas,destFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static byte[] fileToBytes(File file) throws FileNotFoundException{
        InputStream ins = new BufferedInputStream(new FileInputStream(file));
        ByteArrayOutputStream bais = new ByteArrayOutputStream();//字节数组输出流
        byte[] b = new byte[20];
        int len = 0;
        try {
            while((len = ins.read(b))!=-1){
                bais.write(b, 0, len);
            }
            bais.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                ins.close();
                bais.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bais.toByteArray();
    }
    
    public static void BytesTofile(byte[] b,File file) throws FileNotFoundException{
        InputStream bais = new BufferedInputStream(new ByteArrayInputStream(b));//字节数组输入流
        OutputStream out =new BufferedOutputStream(new FileOutputStream(file));
        byte[] bb = new byte[20];
        int len = 0;
        try {
            while((len = bais.read(bb))!=-1){
                out.write(bb, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                out.close();
                bais.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2.6、基本数据类型+String处理流(DataInputStream、DataOutputStream),把数据+类型存放在流中

public class IOTest07 {
    public static void main(String[] args) {
        File srcFile = new File("D:/temp/caililiang2.txt");
        File destFile = new File("D:/temp/caililiang5.txt");
        try {
            //dataOutputStreamTest(destFile);
            dataInputStreamTest(destFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static void dataOutputStreamTest(File file) throws FileNotFoundException{
        DataOutputStream dis = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
        try {
            dis.writeUTF("caililiang");
            dis.writeInt(123);
            dis.writeBoolean(false);
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {dis.close();} catch (IOException e) {e.printStackTrace();}
        }
    }
    
    public static void dataInputStreamTest(File file) throws FileNotFoundException{
        DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
        try {
            System.out.println(dis.readUTF());
            System.out.println(dis.readInt());
            System.out.println(dis.readBoolean());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2.7、引用类型(对象)处理流 (ObjectInputStream、ObjectOutputStream) 把数据+类型存放在流中

public class People implements java.io.Serializable{//实现Serializable接口,就会告诉JVM这个类是要被序列化的类,Serializable是个空接口
    private String name;
    private int age;
    private transient String address;//transient使属性“透明”,不能被序列化
    public People(String name, int age, String address) {
        super();
        this.name = name;
        this.age = age;
        this.address = address;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

public class IOTest08 {
    public static void main(String[] args) {
        People p1 = new People("caililiang",25,"hubei");
        People p2 = new People("caililiang2",25,"hubei2");
        People p3 = new People("caililiang3",25,"hubei3");
        File destFile = new File("D:/temp/caililiang5.txt");
        try {
            //objectOutputStreamTest(destFile,p1,p2,p3);
            objectInputStreamTest(destFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void objectOutputStreamTest(File file,People ... ps) throws FileNotFoundException, IOException{//People ... ps,表示多个People类型的参数
        ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
        for(People p :ps){
            out.writeObject(p);
        }
        out.flush();
        out.close();
    }
    public static void objectInputStreamTest(File file) throws IOException, ClassNotFoundException{
        ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
        Object obj1 =in.readObject();
        Object obj2 =in.readObject();
        Object obj3 =in.readObject();
        if(obj1 instanceof People){
            People p1 =(People) obj1;
            System.out.println(p1.getName());
            System.out.println(p1.getAge());
            System.out.println(p1.getAddress());//地址为transient修饰,未被序列化
        }
        if(obj2 instanceof People){
            People p2 =(People) obj2;
            System.out.println(p2.getName());
            System.out.println(p2.getAge());
            System.out.println(p2.getAddress());//地址为transient修饰,未被序列化
        }
        in.close();
    }
}

2.8、Closeable接口,实现同时关闭多个流

public class FileUtil {
    public static void close(Closeable ... io){//同时关闭多个流
        for(Closeable i :io){
            try {
                if(i!=null){i.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static  void closeAll(T ... io){//泛型实现关闭多个实现了Closeable接口的流
        for(Closeable i :io){
            try {
                if(i!=null){i.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2.9、打印流(printStream)

public class IOTest10 {
    public static void main(String[] args) throws FileNotFoundException {
        test2();
    }
    public void test1() throws FileNotFoundException{
        System.out.println("hello World !!!");
        PrintStream out = System.out;//输出流 控制台输出
        PrintStream err = System.err;
        InputStream in = System.in;//输入流 键盘输入
        out.println("caililiang");
        err.println("caililiang");
        PrintStream out2 = new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("D:/temp/caililiang5.txt"))));
        Scanner sc = new Scanner(in);
        System.out.println("请输入:");
        out2.println(sc.nextLine());
        out2.flush();
        out2.close();
    }   
    public static void test2() throws FileNotFoundException{
        //setOut重定向标准输出流
        //setIn重定向标准输入流
        System.setIn(new BufferedInputStream(new FileInputStream(new File("D:/temp/caililiang2.txt"))));
        Scanner sc = new Scanner(System.in);//Scanner扫描输入
        System.out.println(sc.nextLine());//此时标准输入流变为文件输入
        System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("D:/temp/caililiang5.txt")))));
        System.out.println("asfsdfss");
        System.out.append("sfs121");
        System.out.flush();
        System.out.close();
        System.out.append("sfs121");//关闭之后不生效
    }
}

2.10、文件的分割与合并(利用RandomAccessFile实现)

public class FileSplit {
    private File file;//分割的文件
    private int count;//分割的块数
    private long blockSize;//每块的大小
    private long fileLength;//文件的总大小
    private String destPath;//分割后的文件存放目录
    private Vector names;//每个文件块的名称
    public FileSplit(File file){}
    public FileSplit(File file,long blockSize,String destPath){
        this.file = file;
        this.blockSize = blockSize;
        this.destPath = destPath;
        init();
    }
    public void init(){
        fileLength = file.length();
        count = (int) Math.ceil(fileLength*1.0/blockSize);
        names = new Vector();
        for(int i=0;i0){
                    if(len>readCount){out.write(b, 0, (int)readCount);}else{
                        out.write(b, 0, (int)len);
                    }
                    readCount=readCount-len;
                }
                begainPos+=blockSize;
                out.flush();
                out.close();
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {ran.close();} catch (IOException e) {e.printStackTrace();}
        }
    }
    
    public void fileMerge(String destPath2) throws FileNotFoundException{
        File destFile = new File(destPath2);
        InputStream in = null;
        OutputStream out = new BufferedOutputStream(new FileOutputStream(destFile,true));
        int len =0;
        byte[] b = new byte[20];
        for(int i=0;i

你可能感兴趣的:(IO操作)