0
0

More than 1 year has passed since last update.

FileReader

Last updated at Posted at 2023-02-02

FileReader is subclass of InputStreamReader
read() returns char value or -1 if eof occur.

public class Outer {
    public static void main(String[] args) {
        FileReader r = null;
        try {
            r = new FileReader("C:\\dirtest\\testmakefile.txt");
            while(true) {
                int i = r.read();
                if(i!=-1) {
                    System.out.print( Character.toChars(i));
                } else {
                    break;
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if(r!=null) r.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
hello
bye

try with resourceを使うとclose()を書かなくてもblockが終了時に
自動でclose()してくれる

public class Outer {
    public static void main(String[] args) {
        try {
            FileReader r = new FileReader("C:\\dirtest\\testmakefile.txt");
            try (r){
                while(true) {
                    int i = r.read();
                    if(i!=-1) {
                        System.out.print( Character.toChars(i));
                    } else {
                        break;
                    }
                }
            }
        } catch (IOException ex ) {
            ex.printStackTrace();
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0