Java中IO流-22-IO流拷貝檔案練習題
阿新 • • 發佈:2019-01-29
這篇我們來做練習,通過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內容。