首页 > 编程 > Java > 正文

利用Java字节流的缓冲区:录入文件的路径,将文件拷贝到当前项目下

2019-11-08 03:19:57
字体:
来源:转载
供稿:网友

需求:在控制台录入文件的路径,将文件拷贝到当前项目下。 分析: 1,定义方法对键盘录入的路径进行判断,如果是文件,就返回; 2,在主方法中接收该文件; 3,读和写该文件。 程序代码如下:

package cn.edu.jit.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,读和写该文件 * @author Rocky * @param args * @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 b; while((b = bis.read()) != -1) { bos.write(b); } bis.close(); bos.close(); } /* * 定义一个方法,获取键盘录入的文件路径 * 并封装成File对象返回。 * 1.返回值类型是一个File * 2.参数列表无 */ public static File getFile() { //创建键盘录入对象 Scanner scan = new Scanner(System.in); System.out.PRintln("请输入一个文件的路径:"); while(true) { //接收键盘录入的路径(有可能是文件路径也有可能是一个文件夹路径) //封装成File对象,并对其进行判断 File file = new File(scan.nextLine()); if(!file.exists()) { System.out.println("您录入的文件路径不存在,请重新录入:"); } else if(file.isDirectory()) { System.out.println("您录入的是文件夹路径,请重新录入:"); } else { return file; } } }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表