종료시 close는 반드시 호출할 수 있도록 하며, try ~ finally 구문에 넣어주는 것이 좋다.
자세한 내용은 예제를 통해 참조
ex)
public class StreamTest { public StreamTest() { super(); this.test(); } private void test() { String fullPath = "C:"+File.separator+"Users"+File.separator+"Lee"+File.separator+"test"+File.separator+"numbers.txt"; //writeFile(fullPath,10); readFile(fullPath); } private void writeFile(String fullPath, int i) { FileWriter fileWriter=null; BufferedWriter bufferedWriter=null; try { //fileWriter= new FileWriter(fullPath); //write mode. fileWriter= new FileWriter(fullPath, true);//append mode bufferedWriter = new BufferedWriter(fileWriter); for ( int loop=0; loop < i ; loop ++) { bufferedWriter.write(Integer.toString(loop)); bufferedWriter.newLine(); } System.out.println("Write done!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( bufferedWriter!=null) { try { bufferedWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } private void readFile(String fullPath) { FileReader fileReader=null; BufferedReader bufferedReader=null; try { // fileReader= new FileReader(fullPath); bufferedReader = new BufferedReader (fileReader); String data; while((data = bufferedReader.readLine()) != null ){ System.out.println(data); } System.out.println("Read done!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if( bufferedReader!=null) { try { bufferedReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (fileReader != null) { try { fileReader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } private void readFileWithScanner( String fileName) { File file = new File(fileName); Scanner scanner = null; try { scanner = new Scanner(file); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (scanner != null) scanner.close(); } /* 이하 동일, 참조 try { String data = new String(Files.readAllBytes(Paths.get(fileName))); System.out.println(data); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } */ } }
출처 : 자바의 신
'java' 카테고리의 다른 글
NioSample (0) | 2019.09.22 |
---|---|
Serializable interface, transient 예약어, FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream 예제 (0) | 2019.09.22 |
FileWriter 및 BufferedWriter 텍스트기반 처리 (0) | 2019.09.22 |
FileFilter , FileNameFilter interface (0) | 2019.09.21 |
Thread interrupt 및 getState 예제 (0) | 2019.09.21 |