자바 IO BufferedReader이해하기

항상 io관련 코드는 쪼개는 부분과 합치는 부분

나눠서 생각하기 


public class Prob2 {


public static void main(String[] args) {

Prob2 p2 = new Prob2();

p2.printScore("src/data/data2.txt");

}


public void printScore(String fileName) {


BufferedReader br = null;

try {


// 아래 무려 3번이나 포장해야하는 이유가 뭐지?

// ios7계층처럼 7번포장안해서 다행이라 해야함?

br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));

String titleLine=br.readLine();//이사하기위해 쪼개는 단위 결정

//인줄 알았는데 이건 타이틀만 가져오는거네?

//int data = br.read();

System.out.println(titleLine.replaceAll("/", "\t")+"총점");

//위에거는 타이틀만 출력하는거다

//그럼 이제 내용을 출력하면 돼는데

while(true) {

if(titleLine=="") {

break;

}

}


} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


}






정답

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Prob2 { public static void main(String[] args){ Prob2 p2 = new Prob2(); p2.printScore("src/data/data2.txt"); } //콘솔에 출력하기 //data2_output.txt //파일에도 출력하기 - Grad_BufferedWriter.java참고하기 public void printScore(String fileName){ BufferedReader br = null; BufferedWriter bw = null; try { br = new BufferedReader(new FileReader(fileName)); bw = new BufferedWriter(new FileWriter("src/data/data_output.txt")); String titleLine = br.readLine();//title만 다로 한 줄 읽은 내용을 보관 String title = titleLine.replaceAll("/", "\t")+"\t총점"; System.out.println(title); String jumsuLine = "";//readLine으로 읽은 라인을 저장할 변수 String printLine = "";//출력할 문자열을 저장할 변수 printLine = printLine +title; bw.write(printLine+"\n");


  1. while((jumsuLine = br.readLine())!=null) { String[] studentInfo = jumsuLine.split("/"); System.out.print(studentInfo[0]+"\t"); printLine = studentInfo[0]+"\t"; int total = 0; for(int i=1;i<studentInfo.length;i++) { printLine = printLine + studentInfo[i]+"\t"; System.out.print(studentInfo[i]+"\t"); total = total + Integer.parseInt(studentInfo[i]); } System.out.print(total+"\t"); printLine = printLine+total+"\n"; System.out.println(); bw.write(printLine); } } catch (IOException e) { e.printStackTrace(); }finally { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } }

댓글

가장 많이 본 글