Java 中的IO

Java Old IO

Java IO是通過Stream 以block方式讀取數據的。其中包括字節和字符Stream.
下面一個小例子,分別用字節和字符流來讀取文件。

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class OldIOTest {
    static String fileName="c:/test.txt";
    private void readFileByByte(String fileName) {
        BufferedInputStream bufferedInputStream = null;
        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream(new File(fileName)));
            byte[] data = new byte[1024];
            int len;
            while ((len = bufferedInputStream.read(data)) > 0) {
                System.out.println(new String(data, 0, len));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void  readFileByChar(String fileName) {
        BufferedReader bReader= null;
        try {
             bReader=new BufferedReader(new FileReader(new File(fileName)));
             String line;
             while((line=bReader.readLine())!=null){
                 System.out.println(line);
             }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(bReader!=null){
                try {
                    bReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
        OldIOTest oldIOTest = new OldIOTest();
        oldIOTest.readFileByByte(fileName);
        System.out.println("------------------------------------------");
        oldIOTest.readFileByChar(fileName);
    }

}

執行結果;

test java io
this is a test file.
------------------------------------------
test java io
this is a test file.

Java NIO

Java NIO 是通過Buffer以非block方式讀取數據的。NIO 將最耗時的 I/O 操作轉移回操作系統,因而可以極大地提高速度。
其中重要的幾個概念:

  • Channels
  • Buffers
  • Selectors
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOTest {
    static String fileName = "c:/test.txt";

    private void readFile(String fileName) {
        try {
            @SuppressWarnings("resource")
            FileChannel channel = new FileInputStream(new File(fileName)).getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(64);
            while (channel.read(buffer) != -1) {
                buffer.flip();
                while (buffer.hasRemaining()) {
                    System.out.print((char) buffer.get());

                }
                buffer.clear();
            }

            channel.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void write(String fileName) {
        RandomAccessFile randomAccessFile = null;
        try {
            randomAccessFile = new RandomAccessFile(new File(fileName), "rw");
            FileChannel channel = randomAccessFile.getChannel();
            channel.position(randomAccessFile.length());
            ByteBuffer buffer = ByteBuffer.allocate(64);
            buffer.put("\nnew test.".getBytes());
            buffer.flip();
            channel.write(buffer);
            channel.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        NIOTest nioTest = new NIOTest();
        nioTest.write(fileName);
        nioTest.readFile(fileName);

    }
}

執行結果:

test java io
this is a test file.
new test.

參考:
http://tutorials.jenkov.com/java-nio/index.html
https://www.ibm.com/developerworks/cn/education/java/j-nio/j-nio.html

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1 IO(三)No20 1.1Properties 屬性集 【 Properties屬性集,主要用于操作配置屬...
    征程_Journey閱讀 912評論 0 1
  • InputStream java.io.InputStream (implements java.io.Close...
    yang2yang閱讀 616評論 0 5
  • 1 IONo18 1.1IO框架 【 IO:Input Output 在程序運行的過程中,可能需要對一些設備進...
    征程_Journey閱讀 979評論 0 1
  • 簡介 IO操作一般來講比較耗時,可能操作本地的文件、目錄,也可能操作網絡上的資源,影響 IO 操作性能的主要方面是...
    不是錦蕭閱讀 399評論 0 0
  • GCD是蘋果為多核并行運算提出的解決方案,全稱是Grand CentralDispatch.GCD是純C語言的,它...
    Rhprimer閱讀 617評論 0 0