개주 훈련일지/🏋️ 전집중 호흡 훈련

Java에서 txt 파일 읽기, 복사하기, 저장하기

lshfood2 2025. 10. 25. 21:17

[txt 파일 읽어오기]

public static void main(String[] args) {

 

// 파일 읽어오기

String fileName = "D:\\KIM\\resource\\test.txt"; //읽어올 파일의 경로와 파일명 기재

 

// 파일을 읽어오는 Reader

FileReader fr = null;

try {

fr = new FileReader(fileName)

} catch (FileNotFoundException e) {

e.printStackTrace();

}

 

// 데이터를 읽어오는 Reader

BufferedReader br = new BufferedReader(fr);

while(true) {

String line=null;

try {

line = br.readLine(); //한줄씩 읽어오고 line에 대입

} catch (IOException e) {

e.printStackTrace();

}

if(line == null) { // EOF

break; //읽어올 문장이 없어지면 반복문 종료

}

System.out.println(line);

}

 

BufferedReader br = new BufferedReader(new FileReader(FileName));

위와 같이 두 과정을 합쳐 한 줄로 쓸 수도 있다.

이게 더 자주쓰이고 깔끔해서 보기 좋다.

 

[txt 파일 생성하기]

public static void main(String[] args) {

 

// 파일 생성하기

// ★ 덮어쓰기에 유의!

String fileName = "D:\\KIM\\resource\\a.txt";

 

// 파일에 데이터를 생성해주는 Writer

FileWriter fw = null;

try {

fw = new FileWriter(fileName);

} catch (IOException e) {

e.printStackTrace();

}

 

// 데이터화를 담당하는 Writer

BufferedWriter bw = new BufferedWriter(fw);

try {

bw.write("안녕하세요! :D");

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

bw.close();

} catch (IOException e) {

e.printStackTrace();

}

}

 

BufferedWriter bw = new BufferedWriter(new FileWriter(FileName));

이것도 동일하게 두 과정을 하나로 합치면

위와 같이 한 문장으로 정리할 수 있다.

 

[응용편]

txt 파일을 읽어오고 그걸 가공해서

다른 txt 파일을 만들어보자!

 

목표)

숫자 3개를 기재된 파일 데이터를 바탕으로

숫자의 합과 평균이 적힌 새로운 txt파일 생성

public static void main(String[] args) {

String inputFileName = "D:\\KIM\\resource\\a.txt"; //읽어올 파일의 경로와 파일명은 a.txt

String outputFileName = "D:\\KIM\\resource\\b.txt"; //저장할 파일의 경로와 파일명은 b.txt

 

ArrayList<String> al = new ArrayList<>(); //읽어온 파일을 저장할 데이터 배열

ArrayList<Integer> datas = new ArrayList<>(); //읽어온걸 형변환 시켜서 내보낼 데이터

 

// 1. 파일을 불러온다.

try {

BufferedReader br = new BufferedReader(new FileReader(inputFileName));

//파일 읽어오고 그 읽어온 파일의 데이터를 읽으라는 코딩

while(true) {

String line = br.readLine();

if(line == null) {

break;

}

al.add(line);

}

}

catch(Exception e) {

e.printStackTrace();

}

System.out.println("파일 읽어오기 완료");

System.out.println(al);

System.out.println();

 

// 2. 읽은 파일을 가지고 계산한다. 어떻게?

// 2-1. 읽은 파일 => String

// 2-2. String => int 형변환

// 2-3. 형변환된 데이터들을 계산

for(String v:al) {

int i=Integer.parseInt(v); //String v를 Int로 바꾸는 코딩

datas.add(i); //바꾼 Int정보들을 Integer datas에 추가

}

System.out.println("데이터 변환 완료");

System.out.println(datas);

System.out.println();

 

int total = 0;

for(int data:datas) {

total += data;

}

double avg = total*1.0/datas.size(); //int 정수를 소수로 표기하기 위해서 계산 과정에 1.0 소수 곱하기를 추가해주자.

System.out.println("계산 완료");

System.out.println();

// 형 변환된 데이터로 평균과 총합 데이터가 생성되었다.

 

// 3. 결과를 작성한다.

BufferedWriter bw = null;

try {

bw = new BufferedWriter(new FileWriter(outputFileName));

bw.write("총합 "+total+"\n");

bw.write("평균 "+avg);

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

bw.close();

} catch (IOException e) {

e.printStackTrace();

}

}

System.out.println("파일 생성 완료");

System.out.println();

}