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();
}
}
}