JAVA
day14) 파일 입출력
code_learner
2022. 1. 14. 00:05
파일입출력은 출력단위에 따라 바이트 기반과 문자단위로 분류된다.
>출력단위
1. 1byte -> 바이트 기반
2. 문자 -> 문자 기반
[바이트 기반]
1. FileInputStream
File file = new File("파일위치\\test.txt");
//해당하는 파일이 존재하지 않으면, 새로 생성해줌!
try {
file.createNewFile();
FileInputStream fis=new FileInputStream(file);
//또는 FileInputStream fis=new FileInputStream("파일위치\\text.txt");//타입이 다른 생성자 오버로딩
int data;
while((data=fis.read())!=-1) {
//fis.read()메서드는 파일의 끝에 닿으면, -1을 반환함
//.read()를 하면 다음으로 넘어가므로 data로 저장해둔다
//인자가 없으므로 하나씩 불러와서 data에 값을 바로 저장
System.out.print((char)data);//아스키코드로 불러오고, 문자로 보고싶어서 (char)처리함
}
System.out.println();
} catch (IOException e) {//파일을 읽고쓰는데 발생하는 문제 ex) 파일이 깨져있음, 공간 부족
// TODO Auto-generated catch block
e.printStackTrace();
}catch (FileNotFoundException e) {//읽을 파일이 없는 경우
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
System.out.println("파일 읽어오기 끝");
}
2. FileOutputStream
final String path1 = "파일위치\\test";//경로작업을 미리하고
final String path2 = ".txt";//상수화시켜 코더가 수정하지 못하게 작업
int i =1;
try {
FileOutputStream fos = new FileOutputStream(path1+i+path2,true);
//fos는 해당파일이 없으면 생성하여 작성함
//파일이 있었으면 덮어쓰기하여 작성함
//->이어쓰기가능 생성자 오버로딩을 이용, true
fos.write(65);
fos.flush();//★★★파일입출력을 진행할때 뭔가를 작성했다면
fos.close();// 1.해당스트림을 비우고,2. 통로를 닫아야함
} catch (FileNotFoundException e) {//경로가 잘못되어도 발생하는 Exception
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println("fos객체로 파일작성하기 작업완료");
}
3. FileInputStream, FileOutputStream 함수 오버로딩을 이용한 파일출력
public class Test01 {//사진복사, txt문서등을 복사한다.
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("파일위치\\Cat.jpg");
FileOutputStream fos = new FileOutputStream("파일위치\\Cat - 복사본.jpg");
byte[] buff = new byte[3000];//공간 만들기
int len;//사용된 배열수를 저장하는 변수
while((len=fis.read(buff))!=-1) {//buffer공간만큼 -1이 나올만큼 나른다
fos.write(buff, 0, len);//buff의 데이터를 len만큼 write()
}
fos.flush();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
System.out.println("사진복사 실습 완료");
}
}
}
[문자기반]
바이트기반 입출력에서 read메서드를 실행할때 byte배열을 쓴것과는 다르게 문자기반 입출력에서는 char배열을 쓴다.
public static void main(String[] args) {
final String path1 = "경로\\";
final String path2 = ".txt";
int data=0;
try {
FileReader fr = new FileReader(path1+"task"+path2);
char[] buff = new char[3000];
int len = fr.read(buff);//배열의 사용길이 저장
String str="";//파일의 데이터를 저장하기 위한 변수
for (int i = 0; i < len; i++) {
str += buff[i];
}
System.out.println(str);//문자열으로 저장된 데이터
data = Integer.parseInt(str);
System.out.println(data);//int형으로 변환된 데이터
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}