天天看點

Java中IO流-22-IO流拷貝檔案練習題

這篇我們來做練習,通過IO流操作練習,結束位元組流操作學習,下一個學習的知識點是字元流操作。第一個程式設計題是,在控制台輸入一個檔案路徑,拷貝到目前路徑(Eclipse項目根路徑)。第二個練習題就是把控制台輸入字元串寫入到指定的檔案中去。

1.題目:控制台輸入一個檔案路徑,拷貝該檔案到目前路徑

分析:

1)定義方法處理鍵盤錄入,對檔案路徑進行判斷,如果是檔案就傳回

2)傳回的是一個檔案對象,在main函數接收

3)讀寫該檔案,達到拷貝效果。

代碼實作

package io;

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 Test1 {

	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.參數為空
	 * @return
	 */
	public static File getFile() {
		
		Scanner sc = new Scanner(System.in);
		
		while(true) {
			String line = sc.nextLine();
			File file = new File(line);
			
			if(!file.exists()) {
				System.out.println("錄入的檔案對象不存在,請重新輸入!");
			} else if (file.isDirectory()) {
				System.out.println("錄入是一個檔案夾,不是一個檔案,請重新輸入!");
			} else {
				return file;
			}
		}
			
	}

}
           

2.題目:将鍵盤錄入資料拷貝目前路徑下test.txt中,如果遇到quit就結束

分析:

1)建立鍵盤錄入對象

2)建立輸出流對象,關聯test.txt檔案

3)定義無限循環

4)如果遇到quite就退出

5)如果不是quite就寫入到test.txt檔案

6)關閉流操作

具體代碼實作:

package io;

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

public class Test2 {

	public static void main(String[] args) throws IOException {
		
		//1.鍵盤對象
		Scanner sc = new Scanner(System.in);
		
		//2.建立輸出流對象,關聯test.txt
		FileOutputStream fos = new FileOutputStream("text.txt");
		
		//3.定義無限循環
		while(true) {
			String line = sc.nextLine();
			if("quit".equals(line)) {
				break;
			}else {
				fos.write(line.getBytes()); //字元串轉換位元組
				fos.write("\r\n".getBytes()); //換行
			}
		}
		
		fos.close();
		
	}

}
           

運作一下,所輸入幾個英文字元串,然後最後輸入quit,然後對比test.txt内容。

繼續閱讀