java基礎6:I/O

來源:互聯網
上載者:User

標籤:io   javase   


關於Java基礎的文章,我覺得寫得還可以,以前發在了我其它的部落格了,肯定是原創,現在再分享給大家出來。

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

  一、概述1、定義

在變數數組中和對象中存放的資料是暫時的,程式結束後就會丟失。為了能夠永久的儲存資料,需要將其儲存在磁碟中。

java中的I/O技術可以將資料儲存到本地,以達到永久儲存的要求。

2、流

流是一組有序的序列,根據操作的類型,可分為輸入資料流和輸出資料流。


3、IO.體系

位元組流的兩個頂層父類:

1,InputStream  2,OutputStream.


字元流的兩個頂層父類:

1,Reader 2,Writer


這些體系的子類都以父類名作為尾碼。 

而且子類名的首碼就是該對象的功能。




 二、字元流1、字元流的由來:

其實就是:位元組流讀取文字位元組資料後,不直接操作而是先查指定的編碼錶。擷取對應的文字。

在對這個文字進行操作。簡單說:位元組流+編碼錶 

2、FileReader與FileWriter

a、FileWirter寫入文本

<span style="font-size:14px;">FileWriter fw = new FileWriter("d:\\jinfulin.txt"); w.write("dfs");fw.close();</span>

b、FileReader讀取文本

<span style="font-size:14px;">FileReader fr = new FileReader("d:\\jinfulin.txt");int num1 = fr.read();//讀取第一個字元int num2 = fr.read();//再次調用讀取第二個字元(流特性嘛) System.out.println((char)num1);//列印,將數字轉成字元 System.out.println((char)num2);</span>

c、字元緩衝區

<span style="font-size:14px;">FileReader fr = new FileReader("demo.txt");/* * 使用read(char[])讀取文字檔資料。 *   * 先建立字元數組。 */char[] buf = new char[1024];int len = 0;while((len=fr.read(buf))!=-1){//沒有字元了讀到資料位元-1System.out.println(new String(buf,0,len));}<span style="white-space:pre"></span>fr.close();</span>

d、如何將一些文字儲存到硬碟一個檔案中?


3、字元流緩衝區對象--BfferedReader與BufferedWriterBfferedReader與BufferedWriter類就是把緩衝器封裝成了對象,原理是一樣的。
舉例:文本從一個盤複製到另一個盤修改版



 三、位元組流位元組流和字元流的基本操作是相同的,但位元組流還可以操作其他媒體檔案。
多說就是鄙視大家的智商了,舉個例子來看看就好,
例:複製mp3

<span style="font-size:14px;">private static void myStreamCopy() throws IOException {//定義輸入輸出資料流並加緩衝區BufferedOutputStream buffo = new BufferedOutputStream(new FileOutputStream("f:\\copy.mp3"));BufferedInputStream buffi = new BufferedInputStream(new FileInputStream("f:\\風吹麥浪.mp3"));//開始複製int ch = 0;while((ch = buffi.read()) != -1){buffo.write(ch);}//關閉流buffo.close();buffi.close();}</span>


 四、轉換流1、 轉換流的由來:       a、字元流與位元組流之間的橋樑       b、方便了字元流與位元組流之間的操作
2、轉換流的應用:      位元組流中的資料都是字元時,轉成字元流操作更高效。
InputStreamReader :位元組到字元的橋樑。解碼。OutputStreamWriter:字元到位元組的橋樑。編碼。
3、舉例:將控制台上的文字儲存到檔案中
<span style="font-size:14px;"><span style="white-space:pre"></span>/* * 將控制台輸入的文字儲存到檔案中。 */public static void main(String[] args) throws IOException {BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("F:\\jinfulin.txt")));String line =  null;while((line = bufr.readLine()) != null){if("over".equals(line))break;bufw.write(line);System.out.println(line);}bufr.close();bufw.close();}</span>



 

 五、流操作的基本規律

因為流對象太多,開發時不知道用哪個對象合適。弄清規律有助於我們使用。


1,明確源和目的

源:InputStream  Reader

目的:OutputStream  Writer

 

2,明確資料是否是純文字資料。

源:是純文字:Reader

---------否:InputStream

目的:是純文字 Writer

------否:OutputStream

3,明確具體的裝置。

源裝置:

硬碟:File

鍵盤:System.in

記憶體:數組

網路:Socket流

目的裝置:

硬碟:File

控制台:System.out

記憶體:數組

網路:Socket流

 

4,是否需要其他額外功能。

1,是否需要高效(緩衝區);

2,轉換。



 六、File類1、定義:檔案和目錄路徑名的抽象表現形式
2、特點:        1)用來將檔案或檔案夾封裝成對象
        2)方便於對檔案與檔案夾的屬性資訊進行操作
        3)File類的執行個體是不可變的;也就是說,一旦建立,File 對象表示的抽象路徑名將永不改變
        4)File對象可以作為參數傳遞給流的建構函式
3、初始化:
<span style="font-size:14px;">//可以將一個已存在的,或者不存在的檔案或者目錄封裝成file對象。File f1 = new File("c:\\a.txt");File f2 = new File("c:\\","a.txt");File f = new File("c:\\");File f3 = new File(f,"a.txt");File f4 = new File("c:"+File.separator+"abc"+File.separator+"a.txt");</span>

4、 File對象的常見方法。
a、擷取
<span style="font-size:14px;"><span style="white-space:pre"></span>File file = new File("a.txt");String name = file.getName();//擷取檔案名稱(a.txt)String absPath = file.getAbsolutePath();//絕對路徑。String path = file.getPath();//相對路徑long len = file.length();//檔案長度(大小)long time = file.lastModified();//最後修改時間</span>

b、建立於刪除
<span style="font-size:14px;">File dir = new File("f:\\a1\\22\\jin.txt"); boolean b = dir.mkdir();//建立檔案 dir.mkdirs();//建立多級目錄System.out.println(dir.delete());  boolean b = file.createNewFile();//如果不存在就建立</span>
c、判斷
<span style="font-size:14px;"> boolean b = f.exists();// 判斷是否存在。 System.out.println(f.isFile());//是否是檔案System.out.println(f.isDirectory());//是否是一個目錄</span>

d、重新命名
<span style="font-size:14px;"><span style="white-space:pre"></span>File f1 = new File("c:\\kkk.mp3");File f2 = new File("d:\\ccc.mp3");boolean b = f1.renameTo(f2);System.out.println("ccc="+b);</span>

5、 拓展應用a、 擷取目前的目錄下的檔案以及檔案夾的名稱,包含隱藏檔案。
<span style="font-size:14px;">String[] names = file.list();<span style="white-space:pre"></span>if(names == null)//如果為空白就返回,避免出現null 指標異常<span style="white-space:pre"></span>return;System.out.println(names.length);for(String name : names){System.out.println(name);}</span>


b、過濾所有以某某結尾的檔案


c、深度曆遍所有檔案





d、刪掉一個檔案夾(從裡往外刪,遞迴)

<span style="font-size:14px;">public class DeleteAll {public static void main(String[] args) {File dir = new File("f:\\1234");//dir.delete();//直接刪是刪不掉的dirdelete(dir);}private static void dirdelete(File dir) {File[] files = dir.listFiles();if (files == null)return;for (File file : files) {if(file.isDirectory()){//如果是目錄就遞迴dirdelete(file);}//不是目錄就刪掉System.out.println(file.getAbsolutePath() + "----"+ file.delete());}//最後再刪掉根目錄的檔案夾(此時已經空了)System.out.println(dir.getAbsolutePath() + "----"+ dir.delete());}}</span>


 七、Properties類


1、概述

Properties類並不屬於IO包中的類,而是屬於map集合,在前面map集合章節也有提到,不過由於該集合中資料用到流,在這裡說更合適。

2、特點:

  1,該集合中的鍵和值都是字串類型。
  2,集合中的資料可以儲存到流中,或者從流擷取。 通常該集合用於操作以鍵值對形式存在的設定檔。  

3、舉例

定義功能,擷取一個應用程式啟動並執行次數,如果超過5次,給出使用次數已到請註冊的提示。並不要在運行程式。


<span style="font-size:14px;">public static void getAppCount() throws IOException{//將設定檔封裝成File對象。File confile = new File("count.properties");if(!confile.exists()){//健壯性判斷confile.createNewFile();}//集合中的資料來自於一個檔案。 //注意;必須要保證該檔案中的資料是索引值對。//需要使用到讀取流。 FileInputStream fis = new FileInputStream(confile);Properties prop = new Properties();prop.load(fis);//集合中載入一個檔案輸入資料流//從集合中通過鍵擷取次數。String value = prop.getProperty("time");//定義計數器。記錄擷取到的次數。int count =0;if(value!=null){count = Integer.parseInt(value);if(count>=5){throw new RuntimeException("使用次數已到,請註冊,給錢!");}}count++;//將改變後的次數重新儲存到集合中。//將集合中資料存放區到檔案中,使用store方法。prop.setProperty("time", count+"");FileOutputStream fos = new FileOutputStream(confile);prop.store(fos, "注釋.....");fos.close();fis.close();}</span>


 八、最後

由於I/O這部分知識比較多,也比較重要,所有我分成兩篇部落格來寫,歡迎大家看下一篇部落格。


java基礎6:I/O

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.