一、檔案:
在IO包中唯一與檔案相關的類就是 File類。File類中常用的常量和方法
1、建立檔案:指定路徑和將要建立的檔案名稱字以及類型;然後調用 createNewFile()方法
| File file = new File("D:"+File.separator+"MyJavaProgram"+File.separator+"hello.java"); file.createNewFile(); |
2、刪除檔案:指定路徑和檔案,包括類型屬性,然後調用 delete()方法。
| File file = new File("D:"+File.separator+"MyJavaProgram"+File.separator+"hello.java"); file.delete (); |
3、建立檔案目錄:設定路徑後,調用mkdir()方法如在“D:\MyJavaProgram”這個路徑下建立一個名叫“hello”的檔案夾,那麼程式如下:
| File file = new File("D:"+File.separator+"MyJavaProgram"+File.separator+"hello"); file.mkdir(); |
4、列出指定目錄下的全部檔案:File類中有兩個方法:
第一個是列出該目錄下全部檔案的名字,不包含屬性,也就是說,我看到的是hello這個檔案名稱,而不曉得它是word還是txt文本;第二個則是以目錄的形式,包含屬性和名稱,以File檔案數組的形式第一個樣本如下:
| public class FileDemo2{ public static void main(String[] args){ File file = new File("D:"+File.separator+"MyJavaProgram"+File.separator); String[] str = file.list(); for(int i =0; i< str.length;i++){ System.out.println(str[i]); } }} |
第二個樣本如下:
| import java.io.*;public class FileDemo2{ public static void main(String[] args){ File file = new File("D:"+File.separator+"MyJavaProgram"+File.separator); File[] str = file.listFiles(); for(int i =0; i< str.length;i++){ System.out.println(str[i]); } }} |
運行結果:
二、使用RandomAccessFile來寫入讀取指定位置的資料以上File只是用來建立管理檔案等, 但是向檔案中寫入讀取資料,還是得藉助其他類對象。RandomAccessFile類就是用來寫入讀取指定位置的資料的RandomAccessFile類主要完成隨機讀取功能,可以讀取制定位置的內容。
因為在檔案中,所有的內容都是按照位元組存放的,如一個int 整型數就是佔據4個位元組。
從上面常用的方法表中可以看到,RandomAccessFile類中有兩個構造方法。例如,現在用第一個構造方法來完成一個寫入字串和整數的操作——
| import java.io.*;public class RandomAccessFileDemo{ public static void main (String args[])throws Exception{ File file = new File("d:"+File.separator+"MyJavaProgram"+File.separator+"test.txt"); //讀寫入模式,如果檔案不存在則自動建立 RandomAccessFile ramdomFile = new RandomAccessFile(file,"rw"); //寫入2個資料 String name = "girl"; int love = 25257758; //寫字串用writeBytes方法 ramdomFile.writeBytes(name); //寫整型數,用writeInt方法 ramdomFile.writeInt(love); //對檔案的讀寫操作完成後一定要記得關閉 ramdomFile.close(); }} |
結果:
好,現在再示範如何讀取指定位置的資料現在跳過前面“girl”這4個位元組,直接讀取後面的數字
| import java.io.File ;import java.io.RandomAccessFile ;public class RandomAccessFileDemo{ public static void main(String args[]) throws Exception{ File file = new File("d:"+File.separator+"MyJavaProgram"+File.separator+"test.txt"); //讀寫入模式,如果檔案不存在則自動建立 RandomAccessFile randomFile = new RandomAccessFile(file,"rw"); //讀取字串後面的數字,得先跳過前面的字串(佔4個位元組) randomFile.skipBytes(4); int i = randomFile.readInt(); //輸出所讀到的值 System.out.println("讀到的數字是:"+i); //再回頭讀字串,用seek方法設定指標位置 randomFile.seek(0); byte[] temp = new byte[4]; for(int j = 0;j< temp.length;j++){ temp[j] = randomFile.readByte(); } //轉化為字串 String s = new String(temp); System.out.println("讀到的字串是:"+ s); //System.out.println("讀到的字串是"+s); //對檔案的讀寫操作完成後一定要記得關閉 randomFile.close(); }}; |
運行結果是:
這中間遇到了一個問題就是在用System.out.println()列印輸出中文,總是報告編碼警告:
後來確實是編碼格式問題,解決方案是:用記事本開啟java源檔案,然後另存新檔,選擇 ANSI編碼,覆蓋,然後再次編譯,即可消除警告或者錯誤。