개발 공부/JAVA
[JAVA] 파일 입출력
sngynhy
2021. 7. 22. 08:45
[텍스트 파일 입출력]
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileInputOutput {
public static void main(String[] args) {
// [파일 입출력]
// C:\SEONG_JAVA_0622\resource
String uri = "C:\\SEONG_JAVA_0622\\resource\\"; // 디렉토리 경로 저장
File file = new File(uri + "apple.txt"); // 경로 + 파일명.txt
// file = new File("경로\\파일명.txt");
// 해당 경로에 저장된 파일을 가져오는 역할
// 해당 파일이 존재하지 않으면 새로 생성해준다.
try {
file.createNewFile();
} catch (IOException e) {
System.out.println("파일 생성 중 문제 발생!");
} finally {
System.out.println("--- 파일 생성 작업 ---");
}
try {
FileInputStream fis = new FileInputStream(file);
// 파일 데이터 읽어오기
// 객체 생성 시 "경로" or 객체 작성
int data;
while((data=fis.read()) != -1) { // 파일의 마지막 데이터를 읽어들이면 -1 반환!
System.out.print((char) data + " ");
}
System.out.println();
} catch (FileNotFoundException e) {
System.out.println("읽어올 파일에 문제 발생!");
} catch (IOException e) {
System.out.println("파일을 읽어오는 중에 문제 발생!");
} finally {
System.out.println("--- 파일 읽기 완료 ---");
}
try {
FileOutputStream fos = new FileOutputStream(uri + "mango.txt", true);
// 파일에 작성하기
// 해당 경로에 파일이 없다면 새로 생성
// 파일이 있다면 데이터 덮어쓰기 or 추가
// 객체 생성 시 true로 설정하면 추가, false(생략가능)로 설정하면 덮어쓰기
fos.write(65); // 65 = A
fos.flush(); // 버퍼(통로) 비우기
fos.close(); // 통로 닫기
} catch (FileNotFoundException e) {
System.out.println("작성할 파일에 문제 발생!");
} catch (IOException e) {
System.out.println("파일을 작성하는 중에 문제 발생!");
} finally {
System.out.println("--- 파일 작성 완료 ---");
}
}
}
[이미지 파일 입출력]
이미지 파일 복사하여 내보내기
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageInput {
public static void main(String[] args) {
String uri = "C:\\SEONG_JAVA_0622\\resource\\";
try {
FileInputStream fis = new FileInputStream(uri + "image.jpg");
FileOutputStream fos = new FileOutputStream(uri + "m.jpg");
byte[] b = new byte[1000]; // 읽어올 데이터를 저장할 공간
int len;
while ((len=fis.read(b)) != -1) {
fos.write(b, 0, len); // 배열 b에 저장된 내용을 index 0부터 len만큼 출력소스에 작성
}
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
System.out.println("파일 예외 발생!");
} catch (IOException e) {
System.out.println("입출력 처리 예외 발생!");
}
finally {
System.out.println("--- 사진 파일 출력 완료 ---");
}
}
}