[JAVA] 자바 - 파일 처리 (파일 입출력 스트림/파일 복사하기)
by mini_min[JAVA]
자바 - 파일 처리 (파일 입출력 스트림/파일 복사하기)
✔️ FileInputStream 클래스
: 파일 시스템의 파일로 부터 파일 내용을 바이트 스트림으로 읽어 들이기 위해 시용한다.
: InputStream 클래스의 하위 클래스이다.
: 파일이 존재하지 않으면 FileNotFoundException 예외 발생!
// 키보드로 입력한 내용을 파일로 저장하기
String pathname = "test.txt";
int data;
// FileOutputStream : 파일 출력 바이트 스트림~
// 파일이 없으면 만들고, 있으면 지우고 만든다.
try (FileOutputStream fos = new FileOutputStream(pathname)){
System.out.println("문자열 입력 {종료 알아서} ");
while((data=System.in.read())!=-1) {
fos.write(data); // 파일에 저장
}
fos.flush(); // 없어도 저장됨. fos가 닫히니까
System.out.println("파일 저장 완료!");
} catch (IOException e) {
e.printStackTrace();
}
✔️ FileOutputStream 클래스
: 데이터를 파일 시스템의 파일에 바이트 스트림으로 저장하기 위해 사용
: OutputStream 클래스의 하위 클래스이다.
: 기본적으로 파일이 없으면 생성하고, 이미 존재하면 기존 파일에 덮어 써서 기존 내용이 사라진다.
String pathname = "test.txt";
FileOutputStream fos = null;
int data;
try {
File f = new File(pathname);
// 파일에 대한 정보를 구할 수 있는 메소드를 가지고 있는 클래스
//둘 다 가능
//fos = new FileOutputStream(pathname);
// fos = new FileOutputStream(f);
// 파일이 없으면 만들고 있으면 append 용으로 사용
fos = new FileOutputStream(f, true);
System.out.println("문자열(종료 알아서) ? ");
while((data=System.in.read())!=-1) {
fos.write(data);
}
fos.flush();
System.out.println("파일 저장완료 .. ");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(fos != null) {
try {
fos.close();
} catch (Exception e2) {
}
}
}
🔒 문제 : 파일 복사하기
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String source = null, dest = null;
byte [] b = new byte[4096];
int len;
FileInputStream fis = null;
FileOutputStream fos = null;
try {
System.out.println("복사시킬 원본 파일명 ? ");
source = br.readLine();
System.out.println("복사할 대상 파일명은 ? ");
dest = br.readLine();
fis = new FileInputStream(source);
fos = new FileOutputStream(dest);
// 읽어들인 byte 수를 반환하고 읽은 데이터는 b 열에 저장!
while((len=fis.read(b))!=-1) {
fos.write(b, 0, len);
}
fos.flush();
System.out.println("파일 복사 완료~ ");
} catch (Exception e) {
e.printStackTrace();
}finally {
if(fos != null) {
try {
fos.close();
} catch (Exception e2) {
}
}
if(fis!= null) {
try {
fis.close();
} catch (Exception e2) {
}
}
}
'Java' 카테고리의 다른 글
[JAVA] 자바 - 파일 내용 읽어서 일부분만 다른 파일로 저장하기 (문제) (0) | 2022.08.29 |
---|---|
[JAVA] 자바 - 파일 내용 읽어서 콘솔에 출력하기 (0) | 2022.08.29 |
[JAVA] 자바 - 입출력 스트림 (바이트 스트림/문자 스트림/BufferedReader) (0) | 2022.08.28 |
[JAVA] 자바 - 트랜잭션(Transaction) (0) | 2022.08.24 |
[JAVA] 자바 - JDBC CallableStatement 인터페이스 (0) | 2022.08.24 |
블로그의 정보
개발자 미니민의 개발로그
mini_min