m_shige1979のときどきITブログ

プログラムの勉強をしながら学習したことや経験したことをぼそぼそと書いていきます

Github(変なおっさんの顔でるので気をつけてね)

https://github.com/mshige1979

Javaによるnio2での簡単なファイル読み書き

NIO2?

JavaのSE7から出てきたファイル制御が少し簡単になるライブラリです。
ファイルを閉じるときに意味不明なtry-catch文の対応と一緒に組み込まれたのかな?

昔のやつ

Sample02.java
package sample02;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Sample02 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        FileWriter fw;
        BufferedWriter bw;
        PrintWriter pw;
        
        FileReader fr;
        BufferedReader br;
        
        try{
            File f = new File("/tmp/bbb.txt");
            
            // ファイル書き込み
            fw = new FileWriter(f, true);
            bw = new BufferedWriter(fw);
            pw = new PrintWriter(bw);
            
            pw.write("bbb\n");
            pw.close();
            
            // ファイル読み込み
            fr = new FileReader(f);
            br = new BufferedReader(fr);
            String s;
            String s2 = "";
            while((s = br.readLine()) != null){
                s2 += s + "\n";
            }
            System.out.println(s2);
            
        }catch(IOException e){
            e.printStackTrace();
        }
        
    }
    
}

新しいやつ

Sample01.java
package sample01;

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Sample01 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        // 初期設定
        FileSystem fs = FileSystems.getDefault();
        
        // パスを指定
        Path path1 = fs.getPath("/tmp", "aaa1.txt");
        
        try {
            // 簡易書き込み
            Path write;
            write = Files.write(
                    path1, 
                    "aaa\n".getBytes(), 
                    StandardOpenOption.CREATE, 
                    StandardOpenOption.APPEND);
            
            // 簡易読み込み
            byte[] readAllBytes = Files.readAllBytes(path1);
            System.out.println(new String(readAllBytes, "utf-8"));
            
        } catch (IOException ex) {
            Logger.getLogger(Sample01.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
}

aaa
aaa
aaa
aaa

所感

Stringそのまま出力したいんですけど(´・ω・`)
昔の2つ3つのオブジェクトを使用しなくなったのは良かったと思います。
まだ、気になる点は多いですがファイルのオープン、クローズに手間書けないようなことは嬉しい。