1. 程式人生 > >Java基礎之(IO流)

Java基礎之(IO流)

ack 刪除指定文件 數據操作 unit let exceptio 存在 pat .com

  

簡介:

流是一組有順序的,有起點和終點的字節集合,是對數據傳輸的總稱或抽象。即數據在兩設備間的傳輸稱為流,流的本質是數據傳輸,根據數據傳輸特性將流抽象為各種類,方便更直觀的進行數據操作。

一、File類

  java.io.File類:文件和目錄路徑名的抽象表示形式,與平臺無關 File ,能新建、刪除、重命名文件和目錄。但 File 不能訪問文件內容本身,如果需要訪問文件內容本身,則需要使用輸入/輸出流。

  File對象可以作為參數傳遞給流的構造函數

  File類的常見構造方法:

  1、public File(String pathname) 以pathname為路徑創建File對象,可以是絕對路徑或者相對路徑,如果pathname是相對路徑,則默認的當前路徑在系統屬性user.dir中存儲。

  2、public File(String parent,String child) 以parent為父路徑,child為子路徑創建File對象。

技術分享圖片

技術分享圖片
package main.dyh;


import org.junit.Test;

import java.io.File;
import java.io.IOException;

public class TestFile {

    //文件夾操作
    @Test
    public void fun1(){
        File file1 = new File("D:\\aa");
        boolean mkdir = file1.mkdir();//
創建文件夾,D盤之前是沒有文件夾aa的 File file2 = new File("D:\\aa","bb"); boolean mkdirs = file2.mkdirs();//創建文件夾,並在文件夾中創建子文件夾bb File file3 = new File("D:\\"); String[] list = file3.list();//查詢D盤中所有目錄和文件 for (String s : list) { System.out.println(s); } File file4
= new File("D:\\"); File[] files = file4.listFiles();//查詢D盤中所有文件和文件夾,並顯示路徑 for (File file : files) { System.out.println(file); } } //文件操作 @Test public void fun2() throws IOException { File file1 = new File("D:\\a.txt"); boolean newFile = file1.createNewFile();//創建文件,註意的是,如果把該文件建在一個文件夾中,該文件夾必須存在,或者報異常,如果之前有該文件,會覆蓋 //------------------------------- File file2 = new File("D:\\a.txt"); String name = file2.getName();//獲得該文件的完整名稱,包括後綴 System.out.println(name); File file4 = new File("./a.txt"); File absoluteFile = file4.getAbsoluteFile(); System.out.println(absoluteFile); // ------------------------------------------- File filep = new File(".\\test1.txt"); File filea = new File("D:\\workspace\\test\\test1.txt"); System.out.println("-----默認相對路徑:取得路徑不同------"); System.out.println(filep.getPath()); System.out.println(filep.getAbsolutePath()); System.out.println("-----默認絕對路徑:取得路徑相同------"); System.out.println(filea.getPath()); System.out.println(filea.getAbsolutePath()); File file6 = new File("D:\\a\\a.txt"); String parent = file6.getParent();//得到父目錄 System.out.println(parent); File file3 = new File("D:\\a\\a.txt"); boolean nfile = file3.renameTo(new File("D:\\a\\b.txt")); File file7 = new File("D:\\b.txt"); boolean newFile1 = file7.createNewFile(); boolean delete = file7.delete();//刪除指定文件 } /** * 文件檢測 */ @Test public void fun3() { File file1 = new File("D:\\a.txt"); boolean exists = file1.exists();//文件是否存在 System.out.println(exists); boolean bread = file1.canRead();//文件是否可讀 System.out.println(bread); boolean bwrite = file1.canWrite();//文件是否可寫 System.out.println(bwrite); boolean file = file1.isFile(); System.out.println(file); boolean directory = file1.isDirectory();//是否是文件夾 System.out.println(directory); long length = file1.length(); System.out.println(length); long l = file1.lastModified();//返回此抽象路徑名表示的文件最後一次被修改的時間 System.out.println(l); } }
View Code

二、什麽是IO流

  IO流用來處理設備之間的數據傳輸。 Java程序中,對於數據的輸入/輸出操作以”流(stream)” 的方式進行。

  java.io包下提供了各種“流”類和接口,用以獲取不同種類的數據,並通過標準的方法輸入或輸出數據。

  1、輸入流與輸出流概念

  輸入input:讀取外部數據(磁盤、光盤等存儲設備的數據)到程序(內存)中。

  輸出output:將程序(內存)數據輸出到磁盤、光盤等存儲設備中

技術分享圖片

  2、流的分類

  按操作數據單位不同分為:字節流(8 bit),字符流(16 bit)。

  按數據流的流向不同分為:輸入流,輸出流。

  按流的角色的不同分為:節點流,處理流。

技術分享圖片

  Java的IO流共涉及40多個類,實際上非常規則,都是從如下4個抽象基類派生的。 由這四個類派生出來的子類名稱都是以其父類名作為子類名後綴。

技術分享圖片

  處理流與節點流的區別:

  節點流:節點流可以從一個特定的數據源讀寫數據。

  處理流:處理流是“連接”在已存在的流(節點流或處理流)之上,通過對數據的處理為程序提供更為強大的讀寫功能。

技術分享圖片

  3、IO流的體系

技術分享圖片

三、IO流的讀寫操作

  1、InputStream 和 Reader 是所有輸入流的基類。

  InputStream(典型實現:FileInputStream)

  int read()

  int read(byte[] b)

  int read(byte[] b, int off, int len)

  Reader(典型實現:FileReader)

  int read() int read(char [] c)

  int read(char [] c, int off, int len)

  程序中打開的文件 IO 資源不屬於內存裏的資源,垃圾回收機制無法回收該資源,所以應該顯式關閉文件 IO 資源。

技術分享圖片
package main.dyh;

import org.junit.Test;

import java.io.*;

public class TestOutIn {

    @Test
    public void fun1() {
        FileReader fileReader = null;
        try {
            fileReader = new FileReader(new File("D:\\a.txt"));
            char[] c = new char[1024];
            int len = 0;
            while ((len = fileReader.read(c)) != -1){
                System.out.println(new String(c,0,len));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Test
    public void fun2() {
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(new File("D:\\a.txt"));
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = fs.read(b)) != -1){
                System.out.println(new String(b,0,len));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
View Code

  2、OutputStream 和 Writer 也非常相似: (典型實現:FileOutputStream)

  void write(int b/int c);

  void write(byte[] b/char[] cbuf);

  void write(byte[] b/char[] buff, int off, int len);

  void flush();

  void close();

  需要先刷新,再關閉此流,因為字符流直接以字符作為操作單位,所以 Writer 可以用字符串來替換字符數組,即以 String 對象作為參數 :

  void write(String str);

  void write(String str, int off, int len);

技術分享圖片
package main.dyh;

import org.junit.Test;

import java.io.*;

public class TestInput {

    @Test
    public void fun1(){
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(new File("D:\\a.txt"));
            fileWriter.write("HelloWorld!!");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void fun2(){
        FileOutputStream fo = null;
        try {
            fo = new FileOutputStream(new File("D:\\a.txt"));
            fo.write("woaibeijingtiananmen".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fo.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
View Code

四、處理流

  1、緩沖流

  為了提高數據讀寫的速度,Java API提供了帶緩沖功能的流類,在使用這些流類時,會創建一個內部緩沖區數組。

  根據數據操作單位可以把緩沖流分為:

  BufferedInputStream 和 BufferedOutputStream

  BufferedReader 和 BufferedWriter

  緩沖流要“套接”在相應的節點流之上,對讀寫的數據提供了緩沖的功能,提高了讀寫的效率,同時增加了一些新的方法 對於輸出的緩沖流,寫出的數據會先在內存中緩存,使用flush()將會使內存中的數據立刻寫出。

技術分享圖片
package main.dyh;

import org.junit.Test;

import java.io.*;

public class TestBuffer {

    @Test
    public void fun1(){
        BufferedOutputStream bo = null;
        BufferedInputStream bi = null;
        try {
            bo = new BufferedOutputStream(new FileOutputStream("D:\\d.txt"));
            bi = new BufferedInputStream(new FileInputStream("D:\\d.txt"));

           bo.write("zhonghuarenming".getBytes());//把數據寫到硬盤上

           byte[] b = new byte[1024];
           int len = 0;
           while ((len = bi.read(b)) != -1){//把數據讀到內存中
               System.out.println(new String(b,0,len));
           }
           bo.flush();//刷新緩沖區
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                bi.close();
                bo.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
View Code

Java基礎之(IO流)