고급 JAVA

JAVA-입출력-파일 스트림

햄찌개 2020. 9. 28. 09:29

* 파일 읽기 예제

public class T05_FileStreamTest {

	public static void main(String[] args) {
		//FileInputStream 객체를 이용한 파일 내용 읽기
		FileInputStream fis = null;
		try {
			/*//방법 1. 파일 경로 정보를 문자열로 지정하기
			fis=new FileInputStream("d://D_Other/test2.txt");	//객체생성
			*/
			//방법2. (파일 정보를 File객체를 이용하여 지정하기)
			File file = new File("d://D_Other/test2.txt");
			fis=new FileInputStream(file);
			
			int c;	//읽어온 데이터를 저장할 변수
			while ((c=fis.read())!=-1) {
				//읽어온 자료출력하기
				System.out.print((char)c);
			}
			fis.close();
		} catch (FileNotFoundException e) {
			System.out.println("지정한 파일이 없습니다.");
		}
		 catch (IOException e) {
			 System.out.println("알수 없는 입출력 오류입니다.");
		 }

	}

}

* 파일 출력 예제

public class T06_FileStreamTest {

	public static void main(String[] args) {
	//파일에 출력하기
		FileOutputStream fos =null;
		
		try {
			//출력용 OutputStream 객체 생성 
			fos = new FileOutputStream("d://D_Other/out.txt");
			for (char ch = 'a'; ch <= 'z'; ch++) {
				fos.write(ch);
			}
			System.out.println("파일에 쓰기 잡업 완료 ...");
			
			//쓰기 작업 완료후 스트림 닫기 
			fos.close();
			//================================================
			//저장된 파일의 내용을 읽어와 화면에 출력하기
			FileInputStream fis = new FileInputStream("d://D_Other/out.txt");
			
			int c;
			while ((c=fis.read())!=-1) {
				System.out.print((char)c);
			}
			System.out.println();
			System.out.println("출력 끝");
			
			fis.close();
		}catch (IOException e) {
			e.printStackTrace();
		}

	}

}

public class T07_FileWriter {

	public static void main(String[] args) {
		//사용자가 입력한 내용을 그대로 파일로 저장하기
		
		//콘솔(표준 입출력장치)과 연결된 입력용 문자 스트림 생성 
		//inputStreamReader	=> 바이트 기반 스트림을 문자기반 스트림으로 변환해 주는 보조 스트림.
		InputStreamReader isr = new InputStreamReader(System.in);
		
		FileWriter fw = null;	//파일 출력용 문자기반 스트림
		
		try {
			//파일 출력용 문자 스트림 객체 생성
			fw = new FileWriter("d://D_Other/testChar.txt");
			
			int c;
			
			System.out.println("아무거나 입력하세요");
			
			//콘솔에서 입렬때 입력의 끝 표시는 Ctrl + z 키를 누르면 된다.
			while ((c=isr.read())!=-1) {
				fw.write(c); 	//콘솔에서 입력받은 값을 파일에 출력하기
				}System.out.println("작업끝....");
				isr.close();
				fw.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
public class T08_FileReaderTest {
	public static void main(String[] args) throws IOException {
		//문자 기반 스트림을 이용한 파일 내용읽기
		FileReader fr = null;
		
		//문자 단위의 입력을 담당하는 Reader형 객체 생성
		fr = new FileReader("d://D_Other/testChar.txt");
		
		int c;
		
		while ((c=fr.read())!=-1) {
			System.out.print((char)c);
		}
		fr.close();
	}
}