• JavaSE-IO流:【FileInputStream +FileOutputStream完成文件的拷贝 】常用代码及问题记录


    package com.lyq.java.io;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    /*
    使用FileInputStream + FileOutputStream完成文件的拷贝。
    拷贝的过程应该是一边读,一边写。
    使用以上的字节流拷贝文件的时候,文件类型随意,万能的。什么样的文件都能拷贝。
     */
    public class Copy01 {
        public static void main(String[] args) {
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                // 创建一个输入流对象
                fis = new FileInputStream("D:\Data\linux环境部署.txt");
                // 创建一个输出流对象
           // 出现 java.io.FileNotFoundException: D:Others (拒绝访问。)的错误原因:没有指定文件名称及类型
    fos = new FileOutputStream("D:\Others\test.txt"); // 最核心的:一边读,一边写 byte[] bytes = new byte[1024 * 1024]; // 1MB(一次最多拷贝1MB。) int readCount = 0; while((readCount = fis.read(bytes)) != -1) { fos.write(bytes, 0, readCount); } // 刷新,输出流最后要刷新 fos.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 分开try,不要一起try。 // 一起try的时候,其中一个出现异常,可能会影响到另一个流的关闭。 if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } }

    2、File + FileInputStream + FileOutputStream

    package com.lyq.java.io;
    
    import java.io.*;
    
    /*
    使用File + FileInputStream + FileOutputStream完成文件的拷贝。
    拷贝的过程应该是一边读,一边写。
    使用以上的字节流拷贝文件的时候,文件类型随意,万能的。什么样的文件都能拷贝。
     */
    public class Copy03 {
        public static void main(String[] args) {
            File srcFile = new File("D:\Data\linux环境部署.txt");
            File toFile = new File("D:\Others\Othersdocument\test.txt");
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                // 创建一个输入流对象
                fis = new FileInputStream(srcFile);
                // 创建一个输出流对象
                fos = new FileOutputStream(toFile);
    
                // 最核心的:一边读,一边写
                byte[] bytes = new byte[1024 * 1024]; // 1MB(一次最多拷贝1MB。)
                int readCount = 0;
                while((readCount = fis.read(bytes)) != -1) {
                    fos.write(bytes, 0, readCount);
                }
    
                // 刷新,输出流最后要刷新
                fos.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 分开try,不要一起try。
                // 一起try的时候,其中一个出现异常,可能会影响到另一个流的关闭。
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    3、拷贝目录

    package com.lyq.java.io;
    
    import java.io.*;
    
    /*
    拷贝目录
     */
    public class CopyAll {
        public static void main(String[] args) {
            // 拷贝源
            File srcFile = new File("D:\course\02-JavaSE\document");
            // 拷贝目标
            File destFile = new File("C:\a\b\c");
            // 调用方法拷贝
            copyDir(srcFile, destFile);
        }
    
        /**
         * 拷贝目录
         * @param srcFile 拷贝源
         * @param destFile 拷贝目标
         */
        private static void copyDir(File srcFile, File destFile) {
            if(srcFile.isFile()) {
                // srcFile如果是一个文件的话,递归结束。
                // 是文件的时候需要拷贝。
                // ....一边读一边写。
                FileInputStream in = null;
                FileOutputStream out = null;
                try {
                    // 读这个文件
                    // D:course2-JavaSEdocumentJavaSE进阶讲义JavaSE进阶-01-面向对象.pdf
                    in = new FileInputStream(srcFile);
                    // 写到这个文件中
                    // C:course2-JavaSEdocumentJavaSE进阶讲义JavaSE进阶-01-面向对象.pdf
                    String path = (destFile.getAbsolutePath().endsWith("\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\")  + srcFile.getAbsolutePath().substring(3);
                    out = new FileOutputStream(path);
                    // 一边读一边写
                    byte[] bytes = new byte[1024 * 1024]; // 一次复制1MB
                    int readCount = 0;
                    while((readCount = in.read(bytes)) != -1){
                        out.write(bytes, 0, readCount);
                    }
                    out.flush();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return;
            }
            // 获取源下面的子目录
            File[] files = srcFile.listFiles();
            for(File file : files){
                // 获取所有文件的(包括目录和文件)绝对路径
                //System.out.println(file.getAbsolutePath());
                if(file.isDirectory()){
                    // 新建对应的目录
                    //System.out.println(file.getAbsolutePath());
                    //D:course2-JavaSEdocumentJavaSE进阶讲义       源目录
                    //C:course2-JavaSEdocumentJavaSE进阶讲义       目标目录
                    String srcDir = file.getAbsolutePath();
                    String destDir = (destFile.getAbsolutePath().endsWith("\") ? destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\")  + srcDir.substring(3);
                    File newFile = new File(destDir);
                    if(!newFile.exists()){
                        newFile.mkdirs();
                    }
                }
                // 递归调用
                copyDir(file, destFile);
            }
        }
    }

    4、FileReader+FileWriter 文本复制

    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class CopyFile {
        public static void main(String[] args) throws IOException {
            //创建输入流对象
            FileReader fr=new FileReader("F:\新建文件夹\aa.txt");//文件不存在会抛出java.io.FileNotFoundException
            //创建输出流对象
            FileWriter fw=new FileWriter("C:\copyaa.txt");
            /*创建输出流做的工作:
             *      1、调用系统资源创建了一个文件
             *      2、创建输出流对象
             *      3、把输出流对象指向文件        
             * */
            //文本文件复制,一次读一个字符
            copyMethod1(fr, fw);
            //文本文件复制,一次读一个字符数组
            copyMethod2(fr, fw);
            
            fr.close();
            fw.close();
        }
    
        public static void copyMethod1(FileReader fr, FileWriter fw) throws IOException {
            int ch;
            while((ch=fr.read())!=-1) {//读数据
                fw.write(ch);//写数据
            }
            fw.flush();
        }
    
        public static void copyMethod2(FileReader fr, FileWriter fw) throws IOException {
            char chs[]=new char[1024];
            int len=0;
            while((len=fr.read(chs))!=-1) {//读数据
                fw.write(chs,0,len);//写数据
            }
            fw.flush();
        }
    }

    5、高效的缓冲流 :BufferedInputStream +BufferedOutputStream 

    public class BufferedDemo {
        public static void main(String[] args) throws FileNotFoundException {
              // 记录开始时间
            long start = System.currentTimeMillis();
            // 创建流对象
            try (
             BufferedInputStream bis = new BufferedInputStream(new FileInputStream("py.exe"));
             BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copyPy.exe"));
            ){
                  // 读写数据
                int len;
                byte[] bytes = new byte[8*1024];
                while ((len = bis.read(bytes)) != -1) {
                    bos.write(bytes, 0 , len);
                }
                 bos.flush(); 
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 记录结束时间
            long end = System.currentTimeMillis();
            System.out.println("缓冲流使用数组复制时间:"+(end - start)+" 毫秒");
        }
    }
    缓冲流使用数组复制时间:521 毫秒      

     6、ObjectOutputStream+ObjectInputStream

    public class Employee implements java.io.Serializable {
        private static final long serialVersionUID = 1L;
        public String name;
        public String address;
        public transient int age; // transient瞬态修饰成员,不会被序列化
        public void addressCheck() {
          	System.out.println("Address  check : " + name + " -- " + address);
        }
    }
    
    
    public class SerializeDemo{
       	public static void main(String [] args)   {
        	Employee e = new Employee();
        	e.name = "zhangsan";
        	e.address = "beiqinglu";
        	e.age = 20; 
        	try {
          		// 创建序列化流对象
              ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.txt"));
            	// 写出对象
            	out.writeObject(e);
            	// 释放资源
            	out.close();
            	fileOut.close();
            	System.out.println("Serialized data is saved"); // 姓名,地址被序列化,年龄没有被序列化。
            } catch(IOException i)   {
                i.printStackTrace();
            }
       	}
    }
    输出结果:
    Serialized data is saved
    
    
    public class DeserializeDemo {
       public static void main(String [] args)   {
            Employee e = null;
            try {		
                 // 创建反序列化流
                 FileInputStream fileIn = new FileInputStream("employee.txt");
                 ObjectInputStream in = new ObjectInputStream(fileIn);
                 // 读取一个对象
                 e = (Employee) in.readObject();
                 // 释放资源
                 in.close();
                 fileIn.close();
            }catch(IOException i) {
                 // 捕获其他异常
                 i.printStackTrace();
                 return;
            }catch(ClassNotFoundException c)  {
            	// 捕获类找不到异常
                 System.out.println("Employee class not found");
                 c.printStackTrace();
                 return;
            }
            // 无异常,直接打印输出
            System.out.println("Name: " + e.name);	// zhangsan
            System.out.println("Address: " + e.address); // beiqinglu
            System.out.println("age: " + e.age); // 0
        }
    }
    

      

     二、构造方法

    File类

    1、 public File(String pathname) :通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例。
    2、 public File(String parent, String child) :从父路径名字符串和子路径名字符串创建新的 File实例。
    3、 public File(File parent, String child) :从父抽象路径名和子路径名字符串创建新的 File实例。

    File类常用方法

    • public String getAbsolutePath() :返回此File的绝对路径名字符串。
    • public String getPath() :将此File转换为路径名字符串。
    • public String getName() :返回由此File表示的文件或目录的名称。
    • public long length() :返回由此File表示的文件的长度。
    • public boolean exists() :此File表示的文件或目录是否实际存在。
    • public boolean isDirectory() :此File表示的是否为目录。
    • public boolean isFile() :此File表示的是否为文件。
    • public boolean createNewFile() :文件不存在,创建一个新的空文件并返回true,文件存在,不创建文件并返回false
    • public boolean delete() :删除由此File表示的文件或目录。
    • public boolean mkdir() :创建由此File表示的目录。
    • public boolean mkdirs() :创建由此File表示的目录,包括任何必需但不存在的父目录。

    FileInputStream的构造方法

    1、 FileInputStream(File file): 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。
    2、 FileInputStream(String name): 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名name命名。

    FileOutputStream构造方法

    1、 public FileOutputStream(File file):根据File对象为参数创建对象。
    2、 public FileOutputStream(String name): 根据名称字符串为参数创建对象。

    FileReader类构造方法

    1、FileReader(File file): 创建一个新的 FileReader ,给定要读取的File对象。
    2、 FileReader(String fileName): 创建一个新的 FileReader ,给定要读取的文件的字符串名称。

    FileWriter类构造方法

    1、 FileWriter(File file): 创建一个新的 FileWriter,给定要读取的File对象。
    2、FileWriter(String fileName): 创建一个新的 FileWriter,给定要读取的文件的名称。

    字节缓冲流类构造方法

    1、public BufferedInputStream(InputStream in) :创建一个新的缓冲输入流,注意参数类型为InputStream。

    2、public BufferedOutputStream(OutputStream out): 创建一个新的缓冲输出流,注意参数类型为OutputStream。

    字符缓冲流类构造方法

    1、public BufferedReader(Reader in) :创建一个新的缓冲输入流,注意参数类型为Reader。

    2、public BufferedWriter(Writer out): 创建一个新的缓冲输出流,注意参数类型为Writer。

    ObjectOutputStream类

    public ObjectOutputStream(OutputStream out): 创建一个指定OutputStream的ObjectOutputStream。用于序列化操作

    ObjectInputStream类

    public ObjectInputStream(InputStream in): 创建一个指定InputStream的ObjectInputStream。用于反序列化操作

  • 相关阅读:
    Java源码赏析(四)Java常见注解
    Java源码赏析(三)初识 String 类
    Java源码赏析(二)Java常见接口
    Java源码赏析(一)Object 类
    Java随谈(二)对空指针异常的碎碎念
    Java随谈(一)魔术数字、常量和枚举
    jquery.validate 使用--验证表单隐藏域
    jquery.validate使用
    jquery.validate使用
    jquery.validate使用
  • 原文地址:https://www.cnblogs.com/omgliyq/p/14405760.html
Copyright © 2020-2023  润新知