java输入输出16:IO流(数据拷贝文件)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yuming226/article/details/84257614
1、在控制台录入文件的路径,将文件拷贝到当前目录下。

代码实现如下:

package filePackage;

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.util.Scanner;

public class Demo14_Copy {
	public static void main(String[] args) throws Exception {
		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();
	}

	private static File getFile() {
		Scanner scan = new Scanner(System.in);
		while (true) {
			String line = scan.nextLine();
			File file = new File(line);
			if (!file.exists()) {
				System.out.println("录入的文件路径不存在,请重新录入:");
			} else if (file.isDirectory()) {
				System.out.println("录入的是文件夹,请重新录入:");
			} else {
				return file;
			}
		}
	}
}
2、将键盘录入的数据拷贝到当前项目下,键盘录入数据遇到quit是退出
package filePackage;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class Demo15_Copy2 {
	public static void main(String[] args) throws IOException {
		Scanner scan = new Scanner(System.in);
		FileOutputStream fos = new FileOutputStream("text.txt");
		while (true) {
			String line = scan.nextLine();
			if ("quit".equals(line)) {
				break;
			} 
			fos.write(line.getBytes());
		}
		
		fos.close();
	}
}

猜你喜欢

转载自blog.csdn.net/yuming226/article/details/84257614