今天的內容:
FileInputStream:
該流可以從文件中讀取數據,它的對象可以用new創建。
使用字符串類型的文件名創建一個輸入流對象讀取文件:
InputStream f = new FileInputStream("c:/java/hello");
也可以使用一個文件對象來創建一個輸入流對象讀取文件,首先要用File()方法來創建一個文件對象:
File f = new File("c:/java/hello"); InputStream out = new File InputStream(f);
FileOutputStream的創建方法類似.(如果文件不存在則會創建該文件)
兩個類的綜合實例:
package some; import java.io.*; public class some{ public static void main(String[] args) { try { byte bWrtie[] = {11,21,3,40,5}; OutputStream os = new FileOutputStream("test.txt"); for (int x = 0; x < bWrtie.length; x++) { os.write(bWrtie[x]); } os.close(); InputStream is = new FileInputStream("test.txt"); int size = is.available(); for (int i = 0; i < size; i++) { System.out.print((char)is.read()+" "); } is.close(); } catch (IOException e) { // TODO: handle exception System.out.println("Exception"); } } }
由於文件寫入的時候使用的是二進制格式所以輸出會有亂碼,解決方案:
package some; import java.io.*; public class some{ public static void main(String[] args) throws IOException { File f = new File("a.txt"); FileOutputStream fop = new FileOutputStream(f); OutputStreamWriter writer = new OutputStreamWriter(fop,"gbk"); writer.append("中文輸入"); writer.append("\r\n");// /r/n是常用的換行轉義字符,有的編譯器不認識/n writer.append("English"); writer.close();//關閉寫入流,同時把緩沖區的內容寫到文件里 fop.close();//關閉輸出流 FileInputStream fip =new FileInputStream(f); InputStreamReader reader = new InputStreamReader(fip,"gbk"); StringBuffer s = new StringBuffer(); while (reader.ready()) { s.append((char) reader.read()); } System.out.println(s.toString()); reader.close(); fip.close(); } }
ByteArrayInputStream類:
創建方式:
//用接受字節數組作為參數 ByteArrayInputStream bArray = new ByteArrayInputStream(byte[] a); /*用一個接受字節數字和兩個整形變量off、len。前者表示第一個讀取的字節,len表示讀取字節的長度*/ ByteArrayInputStream bArray = new ByteArrayInputStream(byte[] a, int off, int len);
ByteArrayOutputStream類的創建類似
明天的打算:繼續學習
問題:無