1. 程式人生 > >JAVA NIO 學習總結(上)

JAVA NIO 學習總結(上)

最近看到《java核心技術》的io部分,學習如何訪問檔案,如何以二進位制格式以及文字格式來讀寫檔案,以及jdk後續更新的nio新特性,這裡主要總結nio的新內容。

1.Charset類統一了字符集的管理
我們知道在java中,英文還好,如果碰到中文,很可能就會碰到亂碼問題,例如一箇中文字元如果以UTF-8編碼成二進位制位元組,那就必須要以UTF-8重新解碼成字元,如果用了GBK來解碼,就會出現亂碼。下面是Charset的一個應用場景

    /**
     * 編碼
     */
    public static byte[] encode(String str,String charset){
        Charset charset1 = Charset.forName(charset);
        ByteBuffer encode = charset1.encode(str);
        return
encode.array(); } /** * 解碼 */ public static String decode(byte[] bytes,String charset){ Charset charset1 = Charset.forName(charset); ByteBuffer wrap = ByteBuffer.wrap(bytes); CharBuffer decode = charset1.decode(wrap); return decode.toString(); }

2.Path類抽象了目錄的概念,規範了檔案目錄的操作,可以無需關心你使用windows還是linux。

Path類常見操作如下:

//當前工程的目錄
String baseDir = System.getProperty("user.dir");

Path path = Paths.get(baseDir);
System.out.println("path: "+path.toString());

// 1.如果引數是絕對路徑  則返回絕對路徑
// 2.否則 則在path後面加上 引數
Path resolve = path.resolve("resolve");
System.out
.println("resolve: "+resolve.toString()); //解析path的父路徑 Path resolveSibling = path.resolveSibling("resolveSibling"); System.out.println("resolveSibling: "+resolveSibling.toString()); //resolve 的對立面是 relativize 前面是往後加 後者是往前減 Path relativize = resolve.relativize(path); System.out.println("relativize: "+relativize.toString()); //清除路徑冗餘 Path path1 = Paths.get("a","..","b",".","c"); System.out.println("path1: "+path1.toString()); Path normalize = path1.normalize(); System.out.println("normalize: "+normalize.toString()); //獲取絕對路徑 Path absolutePath = path1.toAbsolutePath(); System.out.println("absolutePath: "+absolutePath.toString());

輸出如下:

path: C:\eclipseMars2\git\IO
resolve: C:\eclipseMars2\git\IO\resolve
resolveSibling: C:\eclipseMars2\git\resolveSibling
relativize: ..
path1: a\..\b\.\c
normalize: b\c
absolutePath: C:\eclipseMars2\git\IO\a\..\b\.\c

更多path的用法在實際中碰到需要自行翻閱api

3.Files類使得檔案操作更加便捷,如果是jdk1.7以下的api,要讀取一個文字檔案需要以下操作

InputStreamReader reader = null;
try {
    reader = new InputStreamReader(new FileInputStream(file),Charset.forName("UTF-8"));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

BufferedReader reader1 = new BufferedReader(reader);

String str = null;
try {
    while((str=reader1.readLine())!=null)
    System.out.println(str);
} catch (IOException e) {
    e.printStackTrace();
}

然後是用File類操作:

//讀取文字檔案,只需傳入檔案的Path路徑和解碼格式即可
List<String> strings = Files.readAllLines(path, Charset.forName("UTF-8"));
System.out.println("字元:");
for(String s : strings){
    System.out.println(s);
}

File類方便讀寫檔案的一個小demo

 Path path = Paths.get("IOTest_1.txt");
if(path.toFile().exists()){
//讀取位元組
byte[] bytes = Files.readAllBytes(path);
System.out.println("位元組:"+bytes);

//讀取字串
List<String> strings = Files.readAllLines(path, Charset.forName("UTF-8"));
System.out.println("字元:");
for(String s : strings){
    System.out.println(s);
}

//寫檔案
String userDir = System.getProperty("user.dir");
Path Files_1 = Paths.get(userDir).resolve("Files_1.txt");
Files.write(Files_1, "明天去玩".getBytes(Charset.forName("UTF-8")));
//追加
Files.write(Files_1, ",因為有事".getBytes(Charset.forName("UTF-8")), StandardOpenOption.APPEND);
}

File類還可以方便的建立inputstream,outputstream,reader,writer物件,以前寫 讀寫檔案感覺很複雜,流的組合寫起來特別麻煩

以前寫的程式碼

BufferedReader read = new BufferedReader(new InputStreamReader(System.in, Charset.forName("UTF-8")));

File:

BufferedReader read = Files.newBufferedReader(Path path, Charset cs)

程式碼就簡潔了很多。