第1章

Similar documents
JavaIO.PDF


untitled

第1章

chp6.ppt

Microsoft Word - 投影片ch14

Java java.lang.math Java Java.util.Random : ArithmeticException int zero = 0; try { int i= 72 / zero ; }catch (ArithmeticException e ) { // } 0,

Swing-02.pdf

Spyder Anaconda Spyder Python Spyder Python Spyder Spyder Spyder 開始 \ 所有程式 \ Anaconda3 (64-bit) \ Spyder Spyder IPython Python IPython Sp

Python a p p l e b e a r c Fruit Animal a p p l e b e a r c 2-2

Chapter 9: Objects and Classes

雲端 Cloud Computing 技術指南 運算 應用 平台與架構 10/04/15 11:55:46 INFO 10/04/15 11:55:53 INFO 10/04/15 11:55:56 INFO 10/04/15 11:56:05 INFO 10/04/15 11:56:07 INFO

1: public class MyOutputStream implements AutoCloseable { 3: public void close() throws IOException { 4: throw new IOException(); 5: } 6:

Microsoft Word - 01.DOC

Microsoft Word - newJavaA4.doc

主程式 : public class Main3Activity extends AppCompatActivity { ListView listview; // 先整理資料來源,listitem.xml 需要傳入三種資料 : 圖片 狗狗名字 狗狗生日 // 狗狗圖片 int[] pic =new

任務二 : 產生 20 個有炸彈的磚塊, 放在隨機的位置編輯 Block 類別的程式碼 import greenfoot.; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) Write a description of class

1.JasperReport ireport JasperReport ireport JDK JDK JDK JDK ant ant...6

Java 程式設計初階 第 5 章:基本輸出入 & 流程控制

(TestFailure) JUnit Framework AssertionFailedError JUnit Composite TestSuite Test TestSuite run() run() JUnit

3.1 num = 3 ch = 'C' 2

OOP with Java 通知 Project 6: 5 月 24 日晚 9 点

2009年9月全国计算机等级考试二级Java真题及答案

javaexample-02.pdf

untitled

Java

EJB-Programming-4-cn.doc

全国计算机技术与软件专业技术资格(水平)考试

9, : Java 19., [4 ]. 3 Apla2Java Apla PAR,Apla2Java Apla Java.,Apla,,, 1. 1 Apla Apla A[J ] Get elem (set A) A J A B Intersection(set A,set B) A B A B

投影片 1

概述

Guava学习之Resources

内 容 简 介 本 书 是 一 本 关 于 语 言 程 序 设 计 的 教 材, 涵 盖 了 语 言 的 基 本 语 法 和 编 程 技 术, 其 中 包 含 了 作 者 对 语 言 多 年 开 发 经 验 的 总 结, 目 的 是 让 初 学 的 读 者 感 受 到 语 言 的 魅 力, 并 掌

java2d-4.PDF

使用MapReduce读取XML文件

Microsoft PowerPoint - SE7ch12.ppt

KillTest 质量更高 服务更好 学习资料 半年免费更新服务

Microsoft PowerPoint - 14Threads.ppt

SDK 概要 使用 Maven 的用户可以从 Maven 库中搜索 "odps-sdk" 获取不同版本的 Java SDK: 包名 odps-sdk-core odps-sdk-commons odps-sdk-udf odps-sdk-mapred odps-sdk-graph 描述 ODPS 基

《大话设计模式》第一章

The Embedded computing platform

Microsoft Word - JAVA Programming Language Homework I ans

<4D F736F F F696E74202D20332D322E432B2BC3E6CFF2B6D4CFF3B3CCD0F2C9E8BCC6A1AAD6D8D4D8A1A2BCCCB3D0A1A2B6E0CCACBACDBEDBBACF2E707074>

PowerPoint Presentation

新版 明解C++入門編

OOP with Java 通知 Project 4: 4 月 19 日晚 9 点

<4D F736F F D20C8EDC9E82DCFC2CEE7CCE22D3039C9CF>

Java 程式設計初階 第 5 章:基本輸出入 & 流程控制

星星排列 _for loop Protected Sub Page_Load(ByVal sender As Object, ByVal e As Dim h As Integer = 7 'h 為變數 ' Dim i, j As Integer For i = 1 To h

第1章

epub 33-8

ebook39-6

單步除錯 (1/10) 打開 Android Studio, 點選 Start a new Android Studio project 建立專案 Application name 輸入 BMI 點下 Next 2 P a g e

《面向对象程序设计A》课程教学大纲Ⅱ4

CC213

Microsoft PowerPoint - 20-string-s.pptx

Learning Java

[Short Essay:] 1. (5 points) Use state-of-memory diagram to describe the differences between x and y declared as follows: double[] x = new double[4];

C H A P T E R 7 Windows Vista Windows Vista Windows Vista FAT16 FAT32 NTFS NTFS New Technology File System NTFS

软件工程文档编制

第3章.doc

Microsoft PowerPoint - C-Ch12.ppt

Microsoft Word - 投影片ch03

Microsoft PowerPoint - VB14.ppt

第1章

用手機直接傳值不透過網頁連接, 來當作搖控器控制家電 ( 電視遙控器 ) 按下按鍵發送同時會回傳值來確定是否有送出 問題 :1. 應該是使用了太多 thread 導致在傳值上有問題 2. 一次按很多次按鈕沒辦法即時反應

JBuilder Weblogic

BOOL EnumWindows(WNDENUMPROC lparam); lpenumfunc, LPARAM (Native Interface) PowerBuilder PowerBuilder PBNI 2

詞 彙 表 編 號 詞 彙 描 述 1 預 約 人 資 料 中 文 姓 名 英 文 姓 名 身 份 證 字 號 預 約 人 電 話 性 別 2 付 款 資 料 信 用 卡 別 信 用 卡 號 信 用 卡 有 效 日 期 3 住 房 條 件 入 住 日 期 退 房 日 期 人 數 房 間 數 量 入

Microsoft Word - ch04三校.doc

untitled

FY.DOC

Microsoft Word doc

96年特種考試第一次司法人員考試試題解答

Microsoft Word - Mail2000_SecurityPatch_

Transcription:

第 12 章 資料檔案管理 1

本章提要 12.1 前言 12.2 資料讀取 Reader/InputStream 12.2.1. Reader/InputStream 12.2.2. System 類別 12.3 資料建檔 Writer/OutputStream 12.4 資料修改 RandomAccessFile 12.5 變更及移動檔案 12.6 檔案列表 12.7 後記 2

12.1 前言 為了減少計算錯誤及提高作業效率, 我們希望幫張老師設計出一支好用的學生資料檔案管理程式功能包括 : 1. 學生基本資料檔案讀取 2. 學生成績建檔 3. 修改成績記錄 4. 成績資料檔更名 5. 成績資料檔列示 3

12.2 資料讀取 Reader/InputStream 基本資料儲存在 Student.txt" 檔案中, 該如何將資料從檔案中取出並顯示到螢幕上呢? Java 提供兩個非常有用的類別, 來幫助我們從檔案中取出所需的資料 : Reader InputStream 4

12.2 資料讀取 Reader/InputStream Reader: 就像是一個檔案的指示器一樣, 指向檔案所存在的地方, 並且有一個讀寫頭對檔案進行讀取 關閉等動作 InputStream: 將資料排成一排, 形成一條如水流般的資料串流 (Stream) 當我們打開資料串流時, 資料就像水龍頭被打開一樣, 從資料串流中流了出來 5

12.2 資料讀取 Reader/InputStream 6

12.2.1. Reader/InputStream Reader 的宣告如下 : Public abstract class Reader extends Object InputStream 的宣告如下 : Public abstract class InputStream extends Object 7

12.2.1. Reader/InputStream Reader 提供的函式 1. close (): 關閉資料流 2. int read (): 讀取資料並傳回, 如果已到結尾, 則傳回 -1 3. int read (char [] array): 將讀取的資料放到 array[] 中, 傳回的資訊為讀取的字元數 4. boolean ready (): 檢查資料是否已準備好, 若是則傳回 true; 反之, 則傳回 false 5. long skip (long n): 跳過 n 個位元組不讀取 8

12.2.1. Reader/InputStream InputStream 提供的函式 1. close () : 關閉資料流 2. int read (): 讀取資料並傳回, 如果已到結尾, 則傳回 -1 3. int read (char [] array): 將讀取的資料放到 array[] 中, 傳回的資訊為讀取的字元數 4. int avaiable (): 傳回目前可以被讀取的字元數 5. long skip (long n): 跳過 n 個位元組不讀取 9

12.2.1. Reader/InputStream Reader 及 InputStream 只是抽象 (Abstract) 類別, 裡面定義的某些功能是有名無實的函式需要用到檔案存取功能時, 必需使用繼承自 Reader 及 InputStream 的 FileReader FileInputStream InputStreamReader 這些類別就真正去撰寫 read close ready skip 等函式內容 10

12.2.1. Reader/InputStream FileReader 是 Reader 及 InputStreamReader 的子類別, 其宣告如下 : Public class FileReader extends InputStreamReader 項 FileReader 類別的建構元次 1 FileReader (File file) 2 FileReader (String filename) 11

12.2.1. Reader/InputStream FileInputStream 是 InputStream 的子類別, 其宣告如下 : Public class FileInputStream extends InputStreamReader 項次 FileInputStream 類別的建構元 1 FileInputStream (File 2 FileInputStream (String filename) 12

12.2.1. Reader/InputStream FileReader FileInputStream InputStreamReader 等類別, 取出的資料皆是以位元組 (byte) 為單位, 屬於較低階的資料處理類別比較方便好用的高階資料處理類別 BufferedReader BufferedInputStream 使得資料讀取以字元 (char) 為單位 13

12.2.1. Reader/InputStream Reader 及 InputStream 類別的繼承關係如 下表所示 抽象類別低階類別高階類別 Reader InputStream FileReader FileInputStream InputStreamReader FilterReader BufferedReader BufferedInputStream 14

12.2.1. Reader/InputStream BufferedReader 是 Reader 的子類別, 其宣告如下 : Public class BufferredReader extends Reader BufferedReader 提供的函式 String readline () : 從檔案一次讀取一列資料, 並以字串方式傳出 15

範例程式 1 學生資料讀取 6 import java.io.*; 13 public ch12_fileread() 14 { 15 try{ // 截取例外情況 16 FileReader fr = new FileReader ("Student.txt"); 17 BufferedReader breader = new BufferedReader(fr); // 開啟資料檔 18 while(true){ 19 String strdata = breader.readline(); // 一次讀取一列 20 if(strdata == null) break; // 如果到達檔尾則結束 21 System.out.println(strData); // 將結果顯示在螢幕上 22 }// end of while 23 fr.close(); 24 breader.close(); // 關閉檔案 25 }catch (IOException e) { 26 System.out.print("Error:" + e); 27 System.exit(1); 28 } 29 } 16

範例程式 1 學生資料讀取 31 public static void main(string[] args) 32 { 33 ch12_fileread fread = new ch12_fileread(); 34 } 執行結果 9143001 林嘉至 03-3314567 桃園縣 9143002 周羽玲 04-2489551 台中縣 9143003 吳大明 02-2217445 台北縣 9143004 黃清德 05-2777415 嘉義縣 9143005 楊得意 02-2125487 台北市 17

範例程式 2 FileInputStream 讀取學生資料 8 public ch12_fileinputstream() 9 { 10 try{ // 截取例外情況 11 File f = new File("Student.txt"); 12 BufferedInputStream input = new BufferedInputStream (new FileInputStream(f)); 13 byte buffer[] = new byte[8]; 14 while(input.available()>0) 15 { input.read(buffer, 0, 8); 16 System.out.print(new String(buffer)); 17 } 18 input.close(); 19 }catch (IOException e) { 20 System.out.print("Error:" + e); 21 System.exit(1); 22 } 23 } 18

範例程式 2 FileInputStream 讀取學生資料 24 public static void main(string[] args) 25 { 26 ch12_fileinputstream finputstream = new ch12_fileinputstream(); 27 } 執行結果 9143001 林嘉至 03-3314567 桃園縣 9143002 周羽玲 04-2489551 台中縣 9143003 吳大明 02-2217445 台北縣 9143004 黃清德 05-2777415 嘉義縣 9143005 楊得意 02-2125487 台北市 19

12.2.2. System 類別 InputStream 除了可以指向檔案外, 也可以指向鍵盤輸入及網路傳入資訊的地方當使用者使用鍵盤輸入資料時, 我們可以利用 InputStream 指向資料輸入的地方, 形成一個資料串流 20

12.2.2. System 類別 那要怎麼知道鍵盤輸入的資料串流在那裡呢? 要如何抓到使用者鍵入的字元呢? System 類別 System 所提供的函式都是 static 的, 所以我們可以直接使用 System 的函式 21

12.2.2. System 類別 System 提供的變數 項次 1 2 3 PrintStream err 標準錯誤資訊輸出串流 InputStream in 標準資料輸入串流 PrintStream out 標準資料輸出串流 System 的變數 22

12.2.2. System 類別 在 System 類別裡面有三個變數 :err in 及 out err 是錯誤訊息的資料串流, 當系統發生錯誤時, 我們可以從 err 中取得錯誤訊息 in: 為鍵盤輸入的資料串流, 當使用者利用鍵盤輸入資料時, 我們可以從 in 中取得所輸入的資料 out: 為標準輸出的資料串流, 當想要將資訊顯示在螢幕上, 可以利用 out 資料串流將資料寫出去 23

out 的例子 12.2.2. System 類別 System.out.println( this is a test"); System.out 負責指向螢幕輸出的地方, 然後再利用 PrintStream 類別提供的 println() 函式, 將資料以一次顯示一列的方式送到 System.out 指定的資料串流上 24

12.2.2. System 類別 在 System 類別裡面 in 就是負責處理輸入資料的資料串流 所以當下達 System.in.read(); 指令時, 就是從鍵盤中取得使用者鍵入的資料 System.in 就指向鍵盤輸入的地方, 而 read() 函式是 InputStream 類別提供的, 用來抓取 System.in 指定地方的資料 25

範例程式 3 從鍵盤輸入資料 8 public static void main(string[] args) 9 { 10 try{ 11 byte buffer[] = new byte[20]; 12 byte score[] = new byte[10]; 13 14 System.out.println(" 輸入一個字串 :" ); 15 System.in.read(buffer); 16 String strdata1 = (new String(buffer)).trim(); 17 18 System.out.println(" 輸入一個數字 :" ); 19 System.in.read(score); 20 int Num =Integer.parseInt((new String(score)).trim()); 26

範例程式 3 從鍵盤輸入資料 22 System.out.println(" 輸入的資料為 :" +strdata1); 23 System.out.println(" 輸入的數值為 :" +Num); 24 25 }catch (IOException e) { 26 System.out.print("Error:" + e); 27 System.exit(1); 28 } 29 } 執行結果 輸入一個字串 :this is a test 輸入一個數字 :50 輸入的資料為 :this is a test 輸入的數值為 :50 27

12.3 資料建檔 Writer/OutputStream 該如何將資料輸入到檔案中呢 Reader 及 InputStream 提供使用者從檔案中取出所需的資料, 相對的,Writer 及 OutputStream 能夠幫助我們將資料寫入檔案中 Writer 及 OutputStream 也是抽象類別, 裡面定義了檔案寫入會用到的寫入 (write) 關閉 (close) 強迫寫入 (flush) 等函式 28

12.3 資料建檔 Writer/OutputStream FileWriter FileOutputStream OutputStreamReader 等類別, 是 Writer 及 OutputStream 的子類別 抽象類別低階類別高階類別 Writer OutputStream FileWriter FileOutputStream OutputStreamWriter FilterWriter BufferedWriter BufferedOutputStream 29

12.3 資料建檔 Writer/OutputStream FileWriter 建構元 項 FileWriter 類別的建構元次 1 FileWriter (File file) 2 FileWriter (String filename) 3 FileWriter (String filename, boolean append) 30

12.3 資料建檔 Writer/OutputStream FileWriter 提供的函式 項次 1 close() 關閉檔案 2 flush() 強迫將資料寫入檔案中 3 4 5 6 write (char [] array) 將 array 陣列資料寫入 FileWriter 的方法 write (char [] array, int index, int len) 將 array 陣列中從第 index 字元開始, 共寫入 len 個字元 write (int c) 只寫入一個字元 write (String str) 寫入一個字串 31

範例程式 4 成績資料檔資料建立 13 public void WriteData(String StudentData) 14 { 15 try{ 16 FileWriter fwriter = new FileWriter("Score.txt", true);// 開檔 17 fwriter.write(studentdata); // 將輸入參數 StudentData 寫入檔案中 18 fwriter.close(); // 關閉檔案 19 } catch (IOException e){} 20 } 32

範例程式 4 成績資料檔資料建立 22 public String InputData() 23 { 24 String Num = "",Name = ""; 25 int Chinese = 0, English = 0, Mathmetic = 0, Computer = 0; 26 27 try { 28 System.out.println("\n 請輸入學生資料 :"); 29 byte score[] = new byte[10]; // 用來存放成績資料 30 31 System.out.print(" 學號 :"); 32 byte buffer[] = new byte[20]; // 用來存放學號資料 33 System.in.read(buffer); // 螢幕輸入 34 Num = (new String(buffer)).trim(); 33

範例程式 4 成績資料檔資料建立 36 if (buffer[0] == (byte) '!') // 判斷是否輸入完畢 37 return "!"; 38 else { 39 System.out.print(" 國文 :"); 40 System.in.read(score); 41 Chinese=Integer.parseInt((new String(score)).trim()); 42 43 System.out.print(" 英文 :"); 44 System.in.read(score); 45 English = Integer.parseInt((new String(score)).trim()); 34

範例程式 4 成績資料檔資料建立 63 public ch12_filewrite_1 () 64 { 65 boolean cont = true; // 是否繼續迴圈的布林值 66 while (cont){ 67 try{ 68 String StudentData = InputData();// 呼叫 InputData 函式 69 if (StudentData == "!") 70 cont = false; // 若使用者鍵入 "!" 表示資料輸入完畢 71 else WriteData(StudentData) ; // 將使用者輸入字串寫入檔案 72 } catch (Exception e) {} 73 } 74 } 35

範例程式 4 成績資料檔資料建立 79 public static void main(string[] args) 80 { 81 ch12_filewrite_1 fw = new ch12_filewrite_1(); 82 System.out.println(" 建檔完畢 "); 83 } 執行結果 請輸入學生資料 : 學號 :9143002 國文 :80 英文 :50 數學 :40 計概 :16 請輸入學生資料 : 學號 :! 36

12.4 資料修改 RandomAccessFile 如何在已完成的成績資料檔中做修正呢 Java 提供 RandomAccessFile 類別來達成 RandomAccessFile 有一個指標, 能夠指出目前讀取到檔案的那個位置, 並且依指示, 在檔案的任意地方做移動我們只需要指出需要修改的地方在那裡, 將該位置以新的資料覆蓋掉, 即可達到修正的目的 37

12.4 資料修改 RandomAccessFile RandomAccessFile 類別繼承了 DataOutput 及 DataInput 的函式, 提供一般檔案常用的功能如 read close ready skip 等 RandomAccessFile 宣告如下 Public class RandomAccessFile extends Object implements DataOutput, DataInput 38

12.4 資料修改 RandomAccessFile RandomAccessFile 類別的建構元 項次 RandomAccessFile 類別的建構元 RandomAccessFile (File file, String mode) mode 為檔案的存取模式, 有 r 及 rw 二種 1 r : 檔案只予許讀取 rw: 可讀取也可寫入 2 RandomAccessFile (String filename, String mode) 3 RandomAccessFile (String filename, boolean append) 39

範例程式 5 RandomAccessFile 14 public ch12_filewrite_2 () 15 { 16 try { 17 byte buffer[] = new byte[20]; // 用來存放學號資料 18 byte score[] = new byte[10]; // 用來存放成績資料 19 RandomAccessFile rf = new RandomAccessFile ("Score.txt", "rw"); // 開啟檔案 20 System.out.println("\n 請輸入學生資料 :"); 21 System.out.print(" 學號 :"); 22 System.in.read(buffer); // 螢幕輸入 23 String inpnum = (new String(buffer)).trim(); // 螢幕輸入的學號 40

範例程式 5 RandomAccessFile 25 while(true){ // 讀取每一列的學號資料 26 byte [] num = new byte[7]; // 檔案內每一筆記錄的學號 27 int n = rf.read(num); 28 String strnum = new String(num); // 取學號部分 29 30 if (n == -1) break; 31 if (strnum.equals(inpnum)) { 32 // 判斷是否為該生的資料 33 System.out.print(" 國文 :"); 34 System.in.read(score); 35 rf.writebytes(" "+(new String(score)).trim()+" "); 41

範例程式 5 RandomAccessFile 45 System.out.print(" 計概 :"); 46 System.in.read(score); 47 rf.writebytes((new String(score)).trim()+"\n"); 48 break; 49 } 50 String strdata = rf.readline(); // 讀取剩下的資料 51 if (strdata == null) break; 52 }// end of while 53 rf.close(); 42

範例程式 5 RandomAccessFile 60 public static void main(string[] args) 61 { 62 ch12_filewrite_2 fw = new ch12_filewrite_2(); 63 } 64 } 執行結果 請輸入學生資料 : 學號 :9143002 國文 :90 英文 :50 數學 :30 計概 :20 43

12.5 變更及移動檔案 如何將檔案放到適當的目錄, 並且修改成指定的名稱呢使用 File 類別來達成這項任務 File 是檔案或目錄的指示器, 指的可能是目錄也可能是檔案 File 宣告如下 Public class File extends Object implements Serializable, Comparable 44

12.5 變更及移動檔案 File 建構元 項次 1 2 3 File 類別的建構元 File (File dir, String filename) 建立一個 dir 加上 filename 的 File 元件 File (String filename) 建立一個 filename 的 File 元件 File (String dir, String filename) 建立一個 dir 加上 filename 的 File 元件 45

12.5 變更及移動檔案 File 提供的函式 項次 1 2 3 4 5 File 的方法 Boolean canread() 查看 File 元件是否可以讀取, 傳回的值為 true/false Boolean canwrite() 查看 File 元件是否可以寫入或修改, 傳回的值為 true/false Boolean createnewfile () 查看檔案建立是否成功, 判斷欲建立檔案的檔名是否已經存在, 若是則不能建立, 傳回 false; 反之, 可以建立, 傳回 true Boolean delete() 刪除目錄或檔案, 若成功, 則傳回 true; 反之, 傳回 false 若刪除的為目錄, 則需為空目錄才能刪除 boolean exists () 查看 File 元件所指的檔案或目錄是否存在, 是的話則回傳 true ; 反之, 回傳 false 46

12.5 變更及移動檔案 File 提供的函式 6 7 8 9 10 String getabsolutepath () 傳回 File 元件的絕對路徑 String getcanonicalpath () 傳回 File 元件的正規路徑 String getname () 傳回 File 元件的目錄或檔案名稱 String getparent () 傳回 File 元件的目錄名稱 Boolean isdirectory() 查看 File 元件是否為目錄 47

12.5 變更及移動檔案 File 提供的函式 11 12 13 14 15 Boolean isfile() 查看 File 元件是否為檔案 String [] list () 若 File 元件指的是一個目錄, 則將目錄下所有的子目錄及檔案名稱放到字串陣列中 Long length() 傳回檔案的長度 blooean mkdir() 建立一個 File 元件所描述的目錄 blooean renameto(file newname) 更改檔案或目錄的名稱 48

範例程式 6 檔案更換目錄及重新命名 13 public ch12_file (String Dir, String FileName) 14 { 15 File f = new File ("Score.txt"); // 舊的檔案元件 16 File newdir = new File (Dir); // 新的檔案元件 - 指向新目錄 17 try{ 18 System.out.println(" 舊的檔案 :" + f.getabsolutepath()); 19 if (newdir.mkdirs()) { // 建立新目錄 20 File newfile = new File (Dir,FileName); 21 f.renameto(newfile); // 路徑改為新目錄, 並更改名稱 22 System.out.println(" 新的檔案 :"+ newfile.getabsolutepath()); 23 System.out.println(" 檔案長度 :" + newfile.length()); 24 } 49

範例程式 6 檔案更換目錄及重新命名 25 else { 26 System.out.println(newDir.getAbsolutePath()+" 建立失敗!"); 27 } 28 } catch (Exception e) {} 29 } 34 public static void main(string[] args) 35 { 36 String Dir = args[0].tostring(); // 輸入新的目錄 37 String FileName = args[1].tostring(); // 輸入新的檔案名稱 38 ch12_file fw = new ch12_file(dir, FileName); 39 } 40 } 50

範例程式 6 檔案更換目錄及重新命名 執行結果 舊的檔案 :D:\Java Book\ch12 檔案及 IO 處理 \ch12\score.txt 新的檔案 :D:\Java Book\ch12 檔案及 IO 處理 \ch12\3a\d3a_score.txt 檔案長度 :174 51

12.6 檔案列表 有沒有方法, 能夠讓我們看到目錄下所有的目錄及檔案呢 File 類別 52

12.6 檔案列表 在 File 提供的函式中,list() 是用來抓取目錄下所包含的子目錄及檔案名稱 針對指定的目錄進行子目錄及檔案展開 File f = new File ( d:\test ); String [] flist = f.list(); For (int i = 0; i< flist.length; i++) System.out.println(flist[i]); 53

12.6 檔案列表 子目錄下面又有子子目錄 File f = new File ( d:\test ); String [] flist = f.list(); For (int i = 0; i< flist.length; i++){ System.out.println(flist[i]); File secondfile = new File (flist[i]); If (secondfile.isdirectory()){ String [] secondflist = secondfile.list(); For (int j = 0; j< secondflist.length; i++) System.out.println(secondflist [j]); } } 54

12.6 檔案列表 如果目錄有很多層, 檔案結構很複雜時, 我們可以利用遞迴函式的方式將子目錄 子子目錄等全部列示出來遞迴函式 Public void Circle (int NC) { if (NC == 10) return; NC ++; Circle (NC); } 55

12.6 檔案列表 目錄展開函式 printfile 利用 list () 取得目錄下的子目錄名稱及檔案名稱利用 isdirectory() 判定是不是子目錄, 如果是, 則繼續呼叫 printfile 展開目錄, 直到所有檔案及目錄皆處理完畢 56

範例程式 7 列示出目錄下所有的目錄及檔案 13 public ch12_file_list (String Dir) 14 { 15 try{ 16 File newdir = new File (Dir); 17 printfile(0,newdir); 18 } catch (Exception e) {} 19 } 57

範例程式 7 列示出目錄下所有的目錄及檔案 21 public void printfile (int Level, File Dir)// 參數 Level 為第幾層目錄 22 { 23 try{ 24 if (Dir.isDirectory()) // 判定是否為目錄 25 { 26 for (int j = 0 ; j <Level*3; j ++) 27 System.out.print(" "); 28 System.out.print(Dir.getName()+"\n 29 String [] FileList = Dir.list(); 30 Level++; 31 for (int i = 0 ; i < FileList.length ; i++) 32 printfile(level,new File(FileList[i])); 33 } 58

範例程式 7 列示出目錄下所有的目錄及檔案 21 public void printfile (int Level, File Dir)// 參數 Level 為第幾層目錄 22 { 23 try{ 24 if (Dir.isDirectory()) // 判定是否為目錄 25 { 26 for (int j = 0 ; j <Level*3; j ++) 27 System.out.print(" "); 28 System.out.print(Dir.getName()+"\n 29 String [] FileList = Dir.list(); 30 Level++; 31 for (int i = 0 ; i < FileList.length ; i++) 32 printfile(level,new File(FileList[i])); 33 } 59

範例程式 7 列示出目錄下所有的目錄及檔案 34 else 35 { 36 for (int j = 0 ; j <Level*3; j ++) 37 System.out.print(" "); 38 System.out.print(Dir.getName()+"\n"); 39 } 40 } catch (Exception e) {} 41 } 45 public static void main(string[] args) 46 { 47 String Dir = args[0].tostring(); // 輸入新的目錄 48 ch12_file_list fw = new ch12_file_list(dir); 49 } 60

執行結果. ch12_fileread.java Student.txt ch12_filewrite_2.java ch12_filewrite_1.java 3A middle term final term D3A_Score.txt 2A middle term final term D2A_Score.txt lineno.exe ch12_fileread.class ch12_filewrite_1.class ch12_filewrite_2.class 3B middle term final term D3B_Score.txt Score.txt ch12_file_list.java ch12_file_list.class ch12_file.java ch12_file.class 61

12.7 後記 本章以張老師成績資料檔案管理為例, 引導您學習關於資料及檔案相關的類別元件及函式 1. Reader 2. Writer 3. InputStream 4. OutputStrem 5. RandomAccessFile 6. File 不論是資料讀取 建立 修改 寫入 或檔案建立 更名等, 都有詳盡的定義及範例說明, 相信讀者應能舉一反三, 充分將這些好用的工具活用在許多地方 62