天天看點

java中檔案的讀寫

Java中檔案讀寫操作的作用是什麼?

回答這個問題時應該先想到的是Java隻是一門語言,我們的一種使用工具而已,這樣答案就明晰了,就是将外來的各種資料寫入到某一個檔案中去,用以儲存下來;或者從檔案中将其資料讀取出來,供我們使用。就如下電影過程,從網絡資源中下載下傳一部電影儲存于你電腦中(寫檔案),當你想看的時候就用播放器打開(讀檔案)。

Java中如何對檔案進行讀寫操作?

先理一理,Java中的流分兩種,位元組流和字元流,其中位元組流的兩個基類是InputStream和OutputStream;字元流的兩個基類是Reader和Writer。所謂檔案流,即我們對檔案的操作留不開流。由此可知我們要用到某個類必然繼承如上的四個基類之一。Java中一切都是類,一切都是對象。自然會想到檔案操作有哪些類:

如下四個直接用到的類:

位元組流中:FileInputStream和FileOutputStream

字元流中:FileReader和FileWriter

找到類就好辦事了。剩下來的就是去找實作方法啦。

兩種選擇方案在這裡,這就牽涉到我們如何選擇合适的檔案讀寫方式呢?

選擇條件的差別:

以位元組為機關讀取檔案,常用于讀二進制檔案,如圖檔、聲音、影像等檔案。

以字元為機關讀取檔案,常用于讀文本,數字等類型的檔案.

至于是否選擇用Buffer來對檔案輸入輸出流進行封裝,就要看檔案的大小,若是大檔案的讀寫,則選擇Buffer這個桶來提供檔案讀寫效率。

如下是簡單運用執行個體:

1、運用位元組流對檔案進行直接讀寫:

注:FileOutputStream(file, true);裡面true參數表示不覆寫原檔案,直接在檔案後面追加添加内容。

public class FileTest

{

static File file = new File("d:/test.txt");

public static void main(String[] args)

try

FileOutputStream out = new FileOutputStream(file, true);

String s = "Hello,world!\r\n";

out.write(s.getBytes());

out.flush();

out.close();

//FileInputStream in = new FileInputStream(file);

//byte [] b = new byte[20];

//in.read(b, 0, b.length);

//System.out.println(new String(b));

//in.close();

} catch (FileNotFoundException e)

e.printStackTrace();

} catch (IOException e)

}

2、運用字元流對檔案進行直接讀寫:

public class File03

FileWriter fw = new FileWriter(file,true);

fw.write("Hello,world!\r\n");

fw.flush();

fw.close();

//FileReader fr = new FileReader(file);

//int i=0;

//String s ="";

//while( ( i = fr.read() )!= -1)

//{

// s = s +(char)i;

//}

//System.out.println(s);

檔案讀寫流用Buffer封裝之後的運用:

1、對位元組流封裝後對檔案進行讀寫:

//FileOutputStream out = new FileOutputStream(file, true);

//BufferedOutputStream bout = new BufferedOutputStream(out);

//String s = "I have a dream!";

//bout.write(s.getBytes());

//bout.flush();

//bout.close();

FileInputStream in = new FileInputStream(file);

BufferedInputStream bin = new BufferedInputStream(in);

byte[] b = new byte[15];

bin.read(b);

bin.close();

System.out.println(new String(b));

2、對字元流封裝後對檔案進行讀寫:

// FileWriter fw = new FileWriter(file, true);

// BufferedWriter bw = new BufferedWriter(fw);

// String nextLine = System.getProperty("line.separator");

// bw.write("Hello,world!" + nextLine);

// bw.flush();

// bw.close();

FileReader fr = new FileReader(file);

BufferedReader br = new BufferedReader(fr);

int i = 0;

String s = "";

String temp = null;

while((temp=br.readLine())!=null)

s = s+temp;

System.out.println(s);