코딩항해기

[실습/JAVA] 파일 입출력 연습하기 (+풀이 0725) 본문

problem solving/과제&실습 코딩

[실습/JAVA] 파일 입출력 연습하기 (+풀이 0725)

miniBcake 2024. 7. 25. 11:48

 

 

[실습]

  1. test.txt 파일의 내용을 불러와서, 몇 번만에 맞췄는지를 다시 test.txt 파일로 작성하기
  2. 이미지.jpg 파일을 복사해서 이미지2.jpg를 생성해주세요!

 

실습 1번 코드

package class01;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

//경로
//D:\경로경로경로

public class Test03 {
	public static void main(String[] args) {
		String url = "D:\\경로경로경로\\";
		String file = "test02.txt";
		int ans = 34;//첫 파일 생성 시 넣을 내용
		String line = "";//파일에서 불러온 내용
		FileWriter fileWriter;
		BufferedWriter writer;
		FileReader fileReader;
		BufferedReader reader;
		//게임
		Scanner sc = new Scanner(System.in);
		int readAns = Integer.parseInt(line);//읽어온 정답
		int max = 50;
		int min = 1;
		int num; //입력값
		int cnt = 0; //시도 횟수
		
		//파일 작성
		try {
			fileWriter = new FileWriter(url+file);
			writer = new BufferedWriter(fileWriter);
			writer.write(""+ans);
			writer.close();
		} 
		catch (IOException e) {
			System.out.println("fileWriter 파일 생성 실패");
			throw new RuntimeException();
		} //파일생성
		
		//파일 불러오기
		try {
			fileReader = new FileReader(url+file);
			reader = new BufferedReader(fileReader);
			while((line += reader.readLine()) != null){
				break;
			}
			reader.close();
		} 
		catch (FileNotFoundException e) {
			System.out.println("fileReader 파일 찾기 실패");
			throw new RuntimeException();
		} 
		catch (IOException e) {
			System.out.println("reader 파일 읽어오기 실패");
			throw new RuntimeException();
		}
		
		
		//게임 시작
		
		System.out.println("UpDown 게임");
		while(true) {
			//입력값 검증
			while(true) {
				System.out.print("정수 입력 >> ");
				cnt++;//값이 올바르던 올바르지 않던 시도횟수는 무조건적으로 증가
				try {
					num = sc.nextInt();//입력값 저장
					//종료조건
					if(min<=num && num<=max) {
						break;
					}
					System.out.println(min+"부터 "+max+" 사이의 정수를 입력하세요.");
				} 
				catch (InputMismatchException e) {
					System.out.println("정수를 입력하세요.");
				}
			}//while
			
			if(num > readAns) {
				System.out.println("Down!");
				max = num-1;
			}
			
			else if(num < readAns) {
				System.out.println("Up!");
				min = num+1;
			}
			
			else {//정답이라면
				try {
					//정답까지 시도 횟수 저장
					fileWriter = new FileWriter(url+file);
					writer = new BufferedWriter(fileWriter);
					writer.write("정답까지의 시도 횟수는 "+cnt+"회 입니다!");
					writer.close(); //writer을 close()하면 버퍼에 담겨있던 값이 전송되며 fileWriter도 함께 닫힌다!
				} 
                catch (IOException e) {
					System.out.println("writer 정답 카운트 저장 실패");
					throw new RuntimeException();
				}
				//저장 후 게임 종료 안내
				System.out.println("정답입니다! 시도 횟수는 "+file+" 파일을 확인해주세요!");
			}
		}//while
		
	}
}

 

실습 1번 발생 오류 해결

 

[Error/JAVA] IOException

오류 메세지 기록IOException입출력 작업 중에 발생하는 예외로, 파일이 존재하지 않거나 파일에 접근할 수 없는 경우 등의 입출력 관련 오류 시 발생  입출력 작업 때에는 IOException

minibcake.tistory.com

 

 

실습 2번 코드

package class01;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;


//경로
//D:\경로경로경로

public class Test04 {
	public static void main(String[] args) {
		String src = "D:\\경로경로경로\\";
		String img = "img1.jpeg";
		String copyImg = "img2.jpeg";
		
		try {
			Files.copy(Paths.get(src+img), Paths.get(src+copyImg));
			//Files.copy(Path, Path) copy()의 매개변수로는 path값이 들어와야한다.
			//Paths.get()을 통해 String을 Path로 형변환 해줄 수 있다.
			System.out.println("파일 복사 성공!");
		} catch (IOException e) {
			System.out.println("파일 복사 실패");
		}
		
	}
}

 

풀이 방식은 많이 달랐다...

 String filePath = "D:\\경로\\";
	      String originFileName = "이미지명.jpeg";
	      String copyFileName = "testCopy.jpeg";

	      try {

	         FileInputStream fis = new FileInputStream(filePath+originFileName);
	         FileOutputStream fos = new FileOutputStream(filePath+copyFileName);

	         byte[] buffer = new byte[1024];
	         int content;
	         while ((content = fis.read(buffer)) != -1) {
	            fos.write(buffer, 0, content);
	         }
	         fos.close();

	      } catch (IOException e) {
	         System.out.println("오류발생!");
	      }