java基礎-JAVA IO

來源:互聯網
上載者:User

標籤:dom   dex   inpu   system   檔案讀取   adl   開啟   ted   cep   

首先JAVA IO為什麼不叫檔案而叫IO? IO其實是對檔案或者網路的抽象,抽象成“流”,“流”是一維的,並且是hi單向流動的:從檔案中讀資料是流、向檔案中寫資料也是流、從網路中讀資料是流、向網路中寫資料也是流等等。

按資料走向來分可以分為輸入資料流,輸出資料流

按處理的資料類型可以分為字元流和位元組流

首先要區分JAVA IO針對的對象, 把自己比作一個程式,向程式寫資料就是Input操作,從程式向外輸出資料就是Output操作

JAVA IO大致分為位元組流和字元流。位元組流:資料時二進位,人不可讀,有InputStream, OutputStream介面。 字元流:資料是基於字元的,認識可讀的,有Reader,Writer介面。

各種流的繼承關係:

反正我第一次看見的時候很頭疼,這麼多類壓根分不清,弄不明白。但是常用的有FileReader, BufferedReader, FileWriter,FileInputStream, FileOutputStream。具體用的時候可以參考API文檔

下面結合實際,寫一下代碼看看具體的介面是如何使用的

File f = new File("src/Java/io/ReadMySelf.java");
System.out.println(f.exists()); //判斷當前檔案是否存在
System.out.println(f.getAbsolutePath()); //得到當前檔案的絕對路徑 F:\JavaLearning\src\Java\io\ReadMySelf.java

諸如此類的操作還有f.canRead(), f.canWrite(), f.canExcute(),f.creatNewFile()會判斷當前檔案是否存在,若不存在會產生新的檔案

File[] files = f.listFiles();  //對files進行遍曆可以的到當前檔案下的所有檔案目錄

 

接下來展示用字元流來讀取檔案:

public class ReadMySelf {    public static void main(String[] args) throws Exception {      File f = new File("src/Java/io/ReadMySelf.java");      FileReader fr = null;      try {          fr = new FileReader(f);          char[] buffer = new char[10];            int length = -1;          while((length = fr.read(buffer)) != -1) {  //每次讀取10個位元組          if(length == 10) {              System.out.print(buffer);          }else {              System.out.println(new String(buffer, 0, length));          }        }      } catch(Exception e) {          e.printStackTrace();      } finally {          if(fr != null) {            fr.close();          }      }
}

也可以使用BufferedReader逐行讀取

public class ReadMySelf {    public static void main(String[] args) throws Exception {    File f = new File("src/Java/io/ReadMySelf.java");    BufferedReader br = null;    try {        br = new BufferedReader(new FileReader(f));        String line = null;        while((line = br.readLine()) != null) {        System.out.println(line);        }    } catch(Exception e) {        e.printStackTrace();    } finally {        if(br != null) {        br.close();        }    }}  

使用StringWriter/FileWriter寫資料,這裡採用StringWriter

public class ReadMySelf {    public static void main(String[] args) throws Exception {    File f = new File("src/Java/io/ReadMySelf.java");    StringWriter sw = new StringWriter();    BufferedReader br = null;    try {        br = new BufferedReader(new FileReader(f));        String line = null;        while((line = br.readLine()) != null) {        sw.write(line);        sw.write("\n");        }        System.out.println(sw.toString());    } catch(Exception e) {        e.printStackTrace();    } finally {         if(br != null) {        br.close();        }    }
}

下面才採用位元組流來讀取一個圖片,並寫入本地程式檔案夾下: 

public class ReadMySelf {    public static void main(String[] args) throws Exception {        BufferedInputStream bis = null;    BufferedOutputStream bos = null;    try {        byte[] buffer = new byte[1024];        File f = new File("F:/JavaLearning/bd_logo.png");        System.out.println(f.exists());        bis = new BufferedInputStream(new FileInputStream("F:/JavaLearning/bd_logo.png"));        bos = new BufferedOutputStream(new FileOutputStream("src/Java/io/a.png"));               int length = -1;         while((length = bis.read(buffer)) != -1) {          bos.write(buffer, 0, length);        }        bos.flush();    } catch(Exception e) {            } finally {        bis.close();        bos.close();    }}

以上都是順序讀寫檔案,還可以使用RandomAccessFile隨機讀寫檔案,有兩種模式“”rw“” “”r“”(唯讀)
RandomAccessFile raf=new RandomAccessFile (file,"rw")
內部包含一個檔案指標,開啟檔案時指標在開頭pointer=0;讀寫操作時指標會往後移動,使用seek(int index); 可以操作指標

public class ReadMySelf {    public static void main(String[] args) throws Exception {        RandomAccessFile file = new RandomAccessFile("src/Java/io/readme.txt", "rw");//若檔案不存在會在本地建立    file.writeInt(20);  //佔4個位元組    file.writeDouble(3.1415926);    //佔8個位元組    file.writeUTF("這是一個UTF字串");     //這個長度寫在當前檔案指標的前兩個位元組出,可以用readShort()讀取    file.writeBoolean(true); //佔1個位元組    file.writeShort(155); //佔2個位元組    file.writeLong(1563231521); //佔8個位元組    file.writeUTF("又是一個UTF字串");        file.writeFloat(35.12f);  //佔4個位元組    file.writeChar(‘a‘); //佔2個位元組        file.seek(0);   //把檔案指標設定到檔案起始處    //以下從file檔案讀取資料,要注意指標位置    System.out.println("-----------從file檔案指定位置讀取資料--------");    System.out.println(file.readInt());    System.out.println(file.readDouble());    System.out.println(file.readUTF());        file.skipBytes(3); //檔案指標跳過三個位元組    System.out.println(file.readLong());}

以上是學JAVA IO時自己做的筆記,還有很多不足,自己還需努力。

 


 

java基礎-JAVA IO

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.