=>API에서 메소드를 보면 처리해야하는 예외 알 수 있음
1. 파일오픈 (생성자에서 처리)
=>OS가 관리하는 리소스인 파일과 연결하는 작업을 처리
=>API를 이용해서 객체를 생성하는 작업
2. 파일엑세스
=>파일을 읽거나 파일에 쓰기
=>byte단위나 문자단위로 데이터를 처리
=>버퍼를 이용해서 효율적으로 IO작업을 처리할 수 있다.
3. 파일닫기(파일연결을 해제-자원을 해제)
=>파일을 닫아줘야 문제가 생기지않음. 꼭 닫아야함
public class FileInputStreamTest {
public static void main(String[] args) {
//API에서 FileInputStream(String name) 들어가면 throw되는 예외 확인할 수 있음.
FileInputStream fis = null;
//try블럭 밖에서도 사용하기 위해서 밖에서 초기화
try {
//1.상대경로
//FileInputStream fis = new FileInputStream("src/data/test.txt");
//2.절대경로
fis = new FileInputStream("C:/backend23/work/javawork/advancedJava/src/data/.txt");
System.out.println((char)fis.read());
} catch (FileNotFoundException e) {
System.out.println("파일 이름이 틀림");
e.printStackTrace();//예외추적
} catch(IOException e) {
System.out.println("파일을 읽는 중에 오류가 발생할 수 있음..");
e.printStackTrace();
}finally {
try {
if(fis!=null)fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
출력 :
j
(파일의 첫번째 글자)
public class FileInputStreamTest2 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
//1.파일오픈
fis = new FileInputStream("src/data/test.txt");
//2.파일엑세스
while(true) {
int data = fis.read();
if(data==-1) {
//file의 끝에 도달하면 멈추게 하기
//( read메소드 return형식)
break;
}
System.out.print((char)data);
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally {
//3.자원반납
//파일이 없거나 해서 생성/오픈이 안되면(?) 초기화 null인상태 그대로
//fis가 null이 아니라는건 fis가 열렸다는뜻이니까
//열어주고 다시 반환하도록 finally구문 작성
try {
if(fis!=null)fis.close();//fis가 null이 아닐때 닫기
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

=>한글출력안됨
public class FileReaderTest {
public static void main(String[] args) {
FileReader fr = null;
try {
//1.파일오픈
fr = new FileReader("src/data/test.txt");
int count = 0;
long start = System.nanoTime();
//2.파일엑세스
while(true) {
int data = fr.read();
if(data==-1) {//파일의 끝을 만난면
break;//반복문을 빠져나오기
}
System.out.print((char)data);
count++;//엑세스 횟수를 체크하기 위한 int형 변수
}
long stop = System.nanoTime();
System.out.println();
System.out.println("실행횟수=>"+count);
System.out.println("실행시간=>"+(stop-start));
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally {
//3.자원반납
try {
if(fr!=null)fr.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}

public class FileWriterTest {
public static void main(String[] args) throws IOException{
//여기서만 이렇게, 원래는 try~catch넣어서.
//위에서 throw하는 건 내가 처리하지 않겠다는뜻
// 기본모드
// FileWriter fw = new FileWriter("src/data/result.txt");
// append모드
// true를 추가하면 데이터 덮어쓰지 않고 추가(로그남는 .. )
FileWriter fw = new FileWriter("src/data/result.txt",true);
// 2.파일엑세스
// wirte메소드는 new line이 포함되지 않음
fw.write(97);//a써짐 아스키로 인식
fw.write(98);//b써짐
fw.write("안녕~~\n");//안녕~~(enter)써짐
// 3.파일닫기- 리소스를 해제
// close가 호출되지 않으면 파일엑세스중으로 판단해서 쓰기가 완료되지 않음
fw.close();
}
}

->덮어쓰지 않은 결과
public class FileCopy {
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("src/api/lang/MathTest.java");
fw = new FileWriter("src/data/output.txt");
int data = 0;//read메소드의 실행결과를 저장할 변수
while((data=fr.read())!=-1) {
//while문의 ()안에 조건을 정의
//파일의 한 문자를 읽어서 -1이 아닐동안 계속 반복작업
fw.write(data);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fr!=null)fr.close();
if(fw!=null)fw.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
실행시간 측정 추가
public class FileCopy {
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("src/api/lang/MathTest.java");
fw = new FileWriter("src/data/output.txt");
int count = 0;
long start = System.nanoTime();
int data = 0;
while((data=fr.read())!=-1) {
fw.write(data);
count++;
}
long stop = System.nanoTime();
System.out.println();
System.out.println("실행횟수=>"+count);
System.out.println("실행시간=>"+(stop-start));
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fr!=null)fr.close();
if(fw!=null)fw.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
output파일

실행횟수와 시간

public class BufferedReaderTest {
public static void main(String[] args) {
/*보조스트림은 자체적으로 입출력을 수행할 수 없고
입출력을 하도록 설정된 클래스를 도와주는 역할을 수행함.*/
FileReader fr = null;
BufferedReader br = null;
try {
// 원시데이터를 이용해서 읽기 작업을 처리할 수 있는 객체 생성
// fr = new FileReader("src/data/test.txt");
// br = new BufferedReader(fr);//이게 더 빠르고 편하다고함..
// 간단버전
br = new BufferedReader(new FileReader("src/data/test.txt"));
// while (true) {
// String line = br.readLine();
// if(line==null) {
// break;
// }
// System.out.println(line);
// }
// 간단버전
String line = "";
while((line = br.readLine())!=null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(br!=null)br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public class FileCopy_BufferedReader {
public static void main(String[] args) {
BufferedReader br = null;
FileWriter fw = null;
try {
br = new BufferedReader(new FileReader("src/api/lang/MathTest.java"));
fw = new FileWriter("src/data/output.txt");
int count = 0;
long start = System.nanoTime();
while(true) {
String line = br.readLine();
if(line==null) break;
fw.write(line);
count++;
}
long stop = System.nanoTime();
System.out.println();
System.out.println("실행횟수=>"+count);
System.out.println("실행시간=>"+(stop-start));
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(br!=null)br.close();
if(fw!=null)fw.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}



public class Grade {
public static void main(String args[]) {
Grade grade = new Grade();
String fileName = "score.txt";
grade.printGrade(fileName);
}
public void printGrade(String fileName) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("src/data/"+fileName));
int total = 0;
int count=0;
while(true) {//라인 하나 처리 반복
String line = br.readLine();//1줄 읽기
if(line==null) {
break;
}
String[] data = line.split(",");
total = total + Integer.parseInt(data[1]);
System.out.println(data[0]+"의 점수는 "+data[1]+"입니다.");//0번째 1번째 반복
count++;
}
System.out.println("모두의 총점은 "+total+"점 입니다.");
System.out.println("모두의 평균은 "+(total/count)+"점 입니다.");
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(br!=null)br.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}




public class FileCompareUtil {
public static void main(String[] args) {
try {
ArrayList<String> list = compareFile("src/data/fstFile1.txt", "src/data/scdFile1.txt");
for(String data : list) {
System.out.println(data);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//main추가
public static ArrayList<String> compareFile(String fstFileName, String scdFileName) throws Exception {
ArrayList<String> result = new ArrayList<>();
BufferedReader fstFile = new BufferedReader(new FileReader(fstFileName));
BufferedReader scdFile = new BufferedReader(new FileReader(scdFileName));
int count = 1;
while(true) {
String line1 = fstFile.readLine();
String line2 = scdFile.readLine();
if(line1==null & line2==null) {
break;
}
if(!line1.equals(line2)) {//line1과 line2가 문자열이 같지 않으면
result.add("LINE "+count+":"+line2);
//line2를 result에 add
}
count++;
}
fstFile.close();
scdFile.close();
return result;
}
}

public class PrintStreamTest {
public static void main(String[] args) throws Exception {//테스트용이니 throw하기
PrintStream ps = new PrintStream("src/data/p_out.txt");
ps.println(3);
ps.println('c');
ps.println(123);
ps.println("hi");
ps.close();
}
}

public class PtrintWriterTest {
public static void main(String[] args) {
//fstFile1을 BufferedReader로 읽어서 PrintWriter로 out.txt로 출력하기
BufferedReader br = null;
PrintWriter pw = null;
try {
br = new BufferedReader(new FileReader("src/data/fstFile1.txt"));
pw = new PrintWriter("src/data/out.txt");
String line="";
while((line = br.readLine())!=null) {
pw.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(br!=null) br.close();
if(pw!=null) pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

본 포스팅은 멀티캠퍼스의 멀티잇 백엔드 개발(Java)의 교육을 수강하고 작성되었습니다.