-
-
Save ksakae1216/8764b7c9e1865f8811ae22350549bafb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jp.org.web; | |
import java.io.BufferedReader; | |
import java.io.FileInputStream; | |
import java.io.InputStreamReader; | |
public class FileReadSample { | |
// ファイル読み込みサンプルメインメソッド | |
public static void main(String[] asrgs) { | |
System.out.println("### Sample File Read Start!!"); | |
FileReadSample fr = new FileReadSample(); | |
String file = "/Users/ksakae1216/work/TestFile.txt"; | |
// fr.oldFileRead(file); // 旧来のファイル読み込み | |
fr.newFileRead(file); // try-with-resourcesでファイル読み込み | |
System.out.println("### Sample File Read End!!"); | |
} | |
// 旧来のファイル読み込み | |
private void oldFileRead(String file) { | |
FileInputStream fi = null; | |
InputStreamReader in = null; | |
BufferedReader br = null; | |
try { | |
fi = new FileInputStream(file); | |
in = new InputStreamReader(fi); | |
br = new BufferedReader(in); | |
// ファイル読み込み | |
String line; | |
while( (line = br.readLine()) != null) { | |
System.out.println(line); | |
} | |
} catch(Exception e) { | |
} finally { | |
try { | |
// クローズ処理 | |
br.close(); | |
in.close(); | |
fi.close(); | |
} catch(Exception fe) { | |
// クローズ失敗 | |
} | |
} | |
} | |
// try-with-resourcesでファイル読み込み | |
private void newFileRead(String file) { | |
try(FileInputStream fi = new FileInputStream(file); | |
InputStreamReader in = new InputStreamReader(fi); | |
BufferedReader br = new BufferedReader(in)) { | |
// ファイル読み込み | |
String line; | |
while( (line = br.readLine()) != null) { | |
System.out.println(line); | |
} | |
} catch(Exception e) { | |
} finally { | |
// クローズ処理不要 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment