자바-13일차(2) 이클립스

최성현·2023년 7월 3일
0

Java

목록 보기
38/46

FileException

String 변수file="파일경로";
BufferedReader 변수1=null; -> 파일을 읽어주는 역할
FileReader 변수2=null; -> 파일을 프로그램에서 가져오는 역할

BufferedReader/FileReader 에는 null값 넣어줘야 작동

변수2=new FileReader(변수file); -> 파일 열기
변수1=new BufferedReader(변수2); -> 파일 읽기

파일에서 내용을 한 줄씩 읽어온다
String 변수4=변수1.readLine();

마지막 줄일 경우 null값을 읽어서, null값일 경우 빠져나가기
if(s==null)
break;

변수=new FileReader(String의 변수); 파일이 없을 경우 예외처리
catch(FileNotFoundException e)

String 변수4=변수1.readLine();의 input/output 예외사항 처리
catch (IOException e)

finally 는 코드 실행을 보장하기 위한 것이지만 JVM이 코드를 실행하지 않는 예외적인 상황에 대해 논의할 것

finally {
/자원은 항상 반대로 반납
fr -> br 해서 br 먼저 닫아줌
try {
br.close(); //-> 파일 읽는걸 닫고
fr.close(); //-> 파일 여는걸 닫는다
} catch (IOException e) {
e.printStackTrace();
}
}

public class FileException_04 {
	
	public static void read()
	{
		String fileName="/Users/sunghyunchoi/Desktop/sist0616/file/monday.txt";
		BufferedReader br=null;
		FileReader fr=null;
		
		try {
			fr=new FileReader(fileName);
			
			System.out.println("파일을 열었어요!");
			
			br=new BufferedReader(fr);
			
			//여러줄 읽을 땐 while(true) 사용
			while(true)
			{
				//메모장에서 내용을 한 줄씩 읽어온다
				String s=br.readLine(); //catch ioexception 한 번 더 하면 에러 제거
				
				//마지막 줄일 경우 null값을 읽어서, null값일 경우 빠져나가기
				if(s==null)
					break;
				
				System.out.println(s);
			}
			
				//예외처리 변수=new FileReader(String의 변수); 파일이 없을 경우
		} catch(FileNotFoundException e) {
			//e.printStackTrace();
			System.out.println("파일이 없어요"+e.getMessage());
				//String s=br.readLine();의 input/output 예외사항 처리 
		}catch (IOException e) {
			
		}finally {
			//자원은 항상 반대로 반납
			//fr -> br 해서 br 먼저 닫아줌
			try {
				br.close(); //-> 파일 읽는걸 닫고
				fr.close(); //-> 파일 여는걸 닫는다
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

	public static void main(String[] args) {
		
		read();
		System.out.println("***메모 정상종료***");
	}

}

FileException2

public class FileBuffer_05 {
	
	public static void read() {
		
		//BufferedReader/FileReader 에는 null값 넣어줘야 작동
		String fileName="/Users/sunghyunchoi/Desktop/sist0616/file/experience.txt";
		BufferedReader br=null;
		FileReader fr=null;
		
		try {
			fr=new FileReader(fileName);
			
			System.out.println("파일을 열었어요");
			
			br=new BufferedReader(fr);
			
			while(true)
			{
				String s=br.readLine();
				
				if(s==null)
					break;
				
				System.out.println(s);
			}
			
		}catch (FileNotFoundException e) {
			
			System.out.println("파일이 없어요"+e.getMessage());
			
		}catch (IOException e) {
			
		}
		try {
			br.close();
			fr.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		

		
	}

	public static void main(String[] args) {

		read();
		System.out.println("***메모 정상 종료***");
	}

}

FileException3 - 숫자

score.txt를 읽고 몇개인지 구하고 총점, 평균까지 구해서 출력

public class FileExcep_06 {
	
	public static void scoreRead()
	{
		String fileName="/Users/sunghyunchoi/Desktop/sist0616/file/score.txt";
		BufferedReader br=null;
		FileReader fr=null;
		int cnt=0;
		int total=0;
		double avg=0;
		
		try {
			fr=new FileReader(fileName);
			
			System.out.println("파일을 열었어요");
			
			br=new BufferedReader(fr);
			
			while(true)
			{
				String s=br.readLine();
				
				if(s==null)
					break;
				
				cnt++;//읽은갯수
				
				total+=Integer.parseInt(s);
				
				System.out.println(s);
			}
			avg=(double)total/cnt;
			
			System.out.println("총점: "+total+"\n총갯수: "+cnt);
			System.out.printf("평균: %.2f ",avg);
			
		} catch (FileNotFoundException e) {
			System.out.println("파일이 없어요 "+e.getMessage());
		} catch (IOException e) {
			
		}
		finally {
			//자원은 오픈한 반대순서로 닫기
			try {
				br.close();
				fr.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	
		
	}
	

	public static void main(String[] args) {
		scoreRead();
		System.out.println("\n**메모 정상 종료**");
	}

}
profile
백엔드 개발자로서 성장해 나가는 성현이의 블로그~

0개의 댓글