[FileReader를 이용하여 한 글자씩 읽기]
public class FileIOtest { public static void main(String[] args) { try { FileReader fr = new FileReader(new File("input.txt")); int oneChar = 0; while((oneChar = fr.read()) != -1) { System.out.print((char)oneChar); } fr.close(); } catch(FileNotFoundException e) { System.out.println(e); } catch(IOException e) { System.out.println(e); } } } | cs |
- 파일의 내용을 읽어와서 char로 하나씩 끝까지 출력한다.
[BufferedReader를 이용하여 줄 단위로 읽기]
public class FileIOtest { public static void main(String[] args) { try { FileReader fr = new FileReader(new File("input.txt")); BufferedReader br = new BufferedReader(fr); String oneLine; while((oneLine = br.readLine()) != null) { System.out.println(oneLine); } br.close(); } catch(FileNotFoundException e) { System.out.println(e); } catch(IOException e) { System.out.println(e); } } } | cs |
[Scanner를 이용해서 읽기]
Scanner scanner = new Scanner(new File("input.txt")); | cs |
- 위와 같이 사용하면 System.in을 이용하여 Scanner를 사용하던 것과 똑같이 파일을 입력으로 받아서 사용할 수 있다.
[BufferedWriter를 이용해서 쓰기]
File file = new File("output.txt"); BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write("1번 줄 내용 작성"); bw.newLine(); // 줄 바꿈 //... | cs |
'Android > Java' 카테고리의 다른 글
Java 기초 내용 정리 (0) | 2018.04.05 |
---|---|
자바(JAVA) - 연산자 5 - 삼항 연산자 (0) | 2015.12.29 |
자바(JAVA) - 연산자 4 - 논리 연산자 (0) | 2015.12.29 |
자바(JAVA) - 연산자 3 - 복잡한 증감연산자 연산 (0) | 2015.12.29 |
자바(JAVA) - 연산자 2 - 자동증감 연산자 (0) | 2015.12.29 |