A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© wangjie 中级黑马   /  2015-10-10 12:37  /  217 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package com.heima.test;
在控制台录入文件的路径,将文件拷贝到当前项目下
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class Test2 {

        /**
         * 在控制台录入文件的路径,将文件拷贝到当前项目下
         * 分析:
         * 1, 定义一个方法  创建键盘录入  并对键盘录入做出判断  时候是一个文件
         * 2,在主方法中接收该文件
         * 3,对该文件进行拷贝(读写该文件)
         * @throws IOException
         */
        public static void main(String[] args) throws IOException {
                File file = getFile();  //获取文件
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getName()));
                int len;
                while((len = bis.read()) != -1){
                        bos.write(len);
                }
                bis.close();
                bos.close();
       
        }
        /*
         * 声明一个方法 并封装成file对象 返回
         * 返回值类型 file
         * 参数列表  无
         */
       
        public static File getFile (){
                Scanner sc = new Scanner(System.in);
                //我们需要不停的录入  直到录入正确的
                while(true){
                        System.out.println("请输入一个文件");
                        String line = sc.next();
                        File file = new File(line);  //将录入的字符串 封装成file对象 好做出判断是否是文件
                        if(!file.exists()){     //判断(文件)是否时候存在
                                System.out.println("你录入的文件路径不存在,请重新录入:");
                        }else if (file.isDirectory()){  //判断是否是文件夹
                                System.out.println("你录入的是文件夹路径,请重新输入:");
                        }else{
                                return file;
                        }
                       
                }
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马