天天看點

IO基礎--OutputStream·FileWriter的基本用法

 基礎文章,僅供自己以及初學者參考。(我其實不算初學者,哈哈)主要是android開發中常常需要記錄log,這部分當初學的的時候沒學清楚,平時都是搬磚過來直接用。今天有時間就看了一下這部分。
           

IO包下的基本結構首先需要了解一下,今天涉及到的5個類是File、OutputStream、InputStream、Writer、Reader。想詳細了解自己可以查,我這裡不做細講,這裡主要介紹一下file輸入輸出。

      現在記錄一個log檔案的生成過程:

      1.檔案生成

String pathname="D:"+File.separator+"LogDir";
            File file=new File(pathname);
            if(!file.exists()){
            	file.mkdirs();
            }
            File text=new File(file, "Log.txt");
            if (!text.exists()) {
				text.createNewFile();
			 }    
           

           檔案生成這裡我建議可以和io分開記,因為File類隻負責檔案的生成,生成過程如上:我們這裡在D://LogDir檔案夾下建立一個Log.txt的文本。當然可以寫成File file=new File(”D://LogDir/Log.txt“); 我建議第一種寫法,一個負責路徑,一個負責檔案名,新手看起來清晰一些。有了檔案才能進行後面的檔案輸入輸出工作。

          2.輸出log

                a.FileWriter(text為1中的file檔案)

private static void StringOut(File text) throws IOException {
		FileWriter fw=new FileWriter(text);
		String log="輸出了log到文本檔案";
		fw.write(log);
		fw.close();
		
	}
           

               b.FileOutputStream

private static void OutText(File text) throws IOException {

FileOutputStream fos=new FileOutputStream(text);
		byte[] b="輸出了log到文本檔案".getBytes();
		fos.write(b);
		fos.close();
		
	}
           

               以上是分别以字元流和位元組流輸出的執行個體(函數名請自動忽略),不使用try...catch是不是看起來簡介多了?

3.輸入log

a.FileReader(為什麼轉成BufferedReader?因為我想用readLine()方法,但是FileReader沒找到)

private static void StringIn(File file) throws IOException {
		FileReader fr=new FileReader(file);
		BufferedReader br=new BufferedReader(fr);
		String s;
		while((s=br.readLine())!=null){
			System.out.println(s);
		}
		fr.close();
		br.close();
	}
           

              b.FileInputStream

private static void InText(File text) throws IOException {
		 FileInputStream fis=new FileInputStream(text);
         byte[] buffer=new byte[512];
         int len;
		 while((len=fis.read(buffer))!=-1){
			  System.out.println(new String(buffer,0,len)); 
		 }
         fis.close();
	}
           

              以上分别是字元流和位元組流的輸入。

               關于位元組流和字元流的差別,位元組是一個byte一個byte的讀,字元流是一個字元一個字元的讀。廢話麼?嘿,一個漢字在編碼下占16bit,即2個byteW;但是他隻是一個字元。是以在讀取字元的情況下,它們大概就這點差別。對于不喜歡用數組的同學,大概會比較喜歡FileReader和Write吧