1. 程式人生 > >I/O輸入輸出

I/O輸入輸出

fileinput 文件 實現 輸入 create 數據 ring NPU file

  1. 流概述
    •   一組有序的數據序列,就好比流淌的小溪,只是小溪流淌的是水,而這個流的是數據,是流入還是流出是相對內存而言的,內存可以認為是數據源的聚集地,而文件從外部流向數據源頭即輸入流,反之,為輸出流。
  2. File類(創建的方式)
  3. 文件輸入、輸出流
  4. 帶緩存的輸入、輸出流
  5. 數據輸入、輸出流
 1 package test.inoutstream;
 2 
 3 
 4 import org.junit.Test;
 5 
 6 import java.io.*;
 7 
 8 public class TestStream {
 9     @Test
10     public void
TestFile(){ 11 File file = new File("word.txt"); 12 if (!file.exists()){ 13 try{ 14 file.createNewFile(); 15 //創建FileOutputStream對象: 16 FileOutputStream outputStream = new FileOutputStream(file); 17 //創建byte型數組 18
byte buy[] = "雞毛換糖了".getBytes(); 19 outputStream.write(buy);//將數組中的信息寫入到文件中 20 outputStream.close(); 21 }catch (Exception e){ 22 e.printStackTrace(); 23 } 24 try { 25 //創建FileInputStream類對象
26 FileInputStream inputStream = new FileInputStream(file); 27 byte byt[] = new byte[1024];//創建byte數組 28 int len = inputStream.read(byt); 29 System.out.println("文件中的信息是:"+ new java.lang.String(byt,0,len)); 30 inputStream.close(); 31 }catch (Exception e){ 32 e.printStackTrace(); 33 } 34 35 } 36 37 } 38 39 /** 40 * FileInputStream和FileOutStream的不足: 41 * 只提供對字節或者字節數組的讀取(比如漢字要轉換) 42 * 可能會出現亂碼 43 * 44 * 引入FileWriter和FileReader 45 * FileReader:從內存中讀文件 46 * FileWriter:往內存中寫文件 47 */ 48 49 /** 50 * 帶緩存的輸入和輸出流 51 * BufferedInputStream與BufferedOutStream 52 *開辟緩存區,多了幾個方法:skip() mark()和reset 53 * BufferedReader和BufferedeWriter類 54 */ 55 56 /** 57 * 數據輸入/輸出流 58 * 運行應用程序以與機器無關的方式從底層輸入流中讀取基本的java數據類型,在讀寫時,無需關註哪個字節 59 */ 60 61 @Test 62 public void TestDataIOStream(){ 63 try{ 64 //創建流對象 65 FileOutputStream fs = new FileOutputStream("word.txt"); 66 //創建DataOutputStream對象,相當於給這個流套了個套子,這樣就可以實現多個功能了 67 DataOutputStream ds = new DataOutputStream(fs); 68 ds.writeUTF("使用WriteUTF方法寫入數據"); 69 ds.writeBytes("使用writeBytes寫入數據"); 70 ds.close(); 71 //創建FileInputStream對象 72 FileInputStream fls = new FileInputStream("word.txt"); 73 DataInputStream dis = new DataInputStream(fls); 74 System.out.println(dis.readUTF()); 75 }catch (Exception e){ 76 e.printStackTrace(); 77 } 78 } 79 }

I/O輸入輸出