在控制台录入文件的路径,将文件拷贝到当前项目下

来源:互联网 发布:淘宝自己退货率怎么看 编辑:程序博客网 时间:2024/05/18 11:18
public static void main(String[] args) throws IOException {
        /**
         * 在控制台录入文件的路径,将文件拷贝到当前项目下
         *
         * 分析:
         *
         * 1,定义方法对键盘录入的路径进行判断,如果是文件就返回
         * 2,在主方法中接收该文件
         * 3,读和写该文件
         * @throws IOException
         */
        BufferedInputStream a =null;
        BufferedOutputStream b=null;
        try{
        File file =getFile();
         a =new BufferedInputStream(new FileInputStream(file));
         b =new BufferedOutputStream(new FileOutputStream(file.getName()));
         int c ;
         while ((c=a.read()) !=-1) {
            b.write(c);
            
        }
        
        }finally{
            try{
                if (a != null)
                    a.close();
            }finally{
                if (b !=null)
                    b.close();
                
            }
            
        }
        
        
        
    }
    /*
     * 定义一个方法获取键盘录入的文件路径,并封装成File对象返回
     * 1,返回值类型File
     * 2,参数列表无
     */
    public static File getFile(){
        Scanner sc =new Scanner(System.in);
        System.out.println("请输入一个文件路径");
        while (true) {
            String a =sc.nextLine();
            File file =new File(a);
            if (!file.exists()) {
                System.out.println("输入错误 路径不存在 请重新输入一个文件路径");
            }else if (file.isDirectory()) {
                System.out.println("输入错误是文件夹 请重新输入一个文件路径");
            }else{
                return file;
            }
        }
    }
阅读全文
0 0
原创粉丝点击