File 클래스
IO 패키지(java.io)에서 제공하는 File 클래스는 파일 크기, 파일 속성, 파일 이름 등의 정보를 얻어내는 기능과 파일 생성 및 삭제 기능을 제공하고 있다.
하지만 파일의 데이터를 읽고 쓰는 기능은 지원하지 않기때문에 스트림을 사용해야한다.
1. FileInputStream 예제 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class FileInputStreamExample { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("경로"); int data; while ((data = fis.read()) != -1) { System.out.write(data); } fis.close(); } catch (Exception e) { e.printStackTrace(); } } } | cs |
2. FileOutputStream 예제 코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class FileOutputStreamExample { public static void main(String[] args) { String originalFileName = "경로"; String targetFileName = ""; FileInputStream fis = new FileInputStream(originalFileName); FileOutputStream fos = new FileOutputStream(targetFileName); int readByteNo; byte[] readBytes = new byte[100]; while((readByteNo = fis.read(readBytes)) != -1) { fos.write(readBytes, 0, readByteNo); } fos.flush(); fos.close(); fis.close(); } } | cs |
'Java' 카테고리의 다른 글
예외 발생 및 회피 (0) | 2019.01.25 |
---|---|
예외 클래스 (0) | 2019.01.25 |
예외 처리 (0) | 2019.01.25 |
Comparable과 Comparator (0) | 2019.01.24 |
01. StringTokenizer 클래스 (0) | 2018.10.04 |