File class는 I/O에 해당하는 클래스가 아니다.


하지만 File을 읽어오거나 쓸 때 사용하며 이 기능을 사용 할 때 Stream과 함께 사용된다.


일반적으로


1. 파일 객체를 만들어 읽어올 경로를 설정하고


2. 읽어올 파일을 Input Stream에 집어 넣고


3. 프로그램에서 Stream을 이용해 작업 한 후


4. 작업한 데이터를 Output Stream에 집어 넣고


5. 파일 객체 만들어 파일을 만들 경로를 설정하여 내보냄


내보낼 때에는 File Input Stream, File Output Stream을 사용한다.



다음 예제는 File 객체의 메소드를 활용한 예제이다.



package chap11.exam04.file;

import java.io.File;

public class FileMain {

	public static void main(String[] args) throws Exception {
		// 폴더 만들기 - File 객체 사용
		File dir = new File("c:/img/temp");
		if(!dir.exists()) { // 폴더가 존재 하지 않을 경우
			System.out.println("폴더 생성");
			dir.mkdirs();
		}		
		
		// 파일 만들기 - File 객체 사용
		 File file = new File("C:/img/temp/test.txt");
		 if(!file.exists()) {
			 System.out.println("파일 생성");;
			 file.createNewFile();
		 }

		 // 폴더 또는 파일에 대한 정보 - File 객체 사용
		 dir = new File("c:/img");
		 // 폴더에 해당하는 파일명
		 String[] fileNames = dir.list();
		 for(String name : fileNames) {
			 System.out.println(name);
		 }
		 
		 // 파일 객체를 뽑아내기
		 File[] files = dir.listFiles();
		 String gubun;
		 for(File f : files) {
			 if(f.isDirectory()) {
				 System.out.println("true");
				 gubun = "[디렉토리]";
			 } else {
				 gubun = "[파일]";
			 }
			 System.out.println(gubun + " " + f.getName() + " / " + f.length() + "byte");
		 }
	}

}


package chap11.exam05.fileinput;

import java.io.File;
import java.io.FileInputStream;

public class FileInputMain {

	public static void main(String[] args) throws Exception {
		// 1. 읽어올 파일 위치 지정
		String path = "C:/img/temp/test.txt";
		
		// 2. 파일 객체 생성
		File file = new File(path);
		
		// 3. 스트림 준비(빨대)
		// FileInputStream은 파일 특화이고 생성자 경로를 문자열로 넣어도 됨
		FileInputStream fis = new FileInputStream(file);
		// fis = new FileInputStream(path);
		
		// 4. 빨아 들인다.
		int data;
		while((data = fis.read())!=-1) { // -1 == EOF
			// 5. 출력(시스템안에서 이루어짐)
			System.out.print((char)data);
		}

		
		// 6. 닫아준다.(빨대 치우기)
		fis.close();
	}

}



package chap11.exam05.fileinput;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class FileOutputMain {

	public static void main(String[] args) throws Exception {
		// 1. 파일 위치 선정(읽어올 곳, 내보낼 곳)
		String pathInput = "C:/img/001.jpg";
		String pathInput2 = "C:/img/10multi.pdf";
		String pathOutput = "C:/img/temp/food.jpg";
		String pathOutput2 = "C:/img/temp/10multi_copy.pdf";
		// 2. 스트림 준비(input, output)
		FileInputStream fis = new FileInputStream(pathInput);
		FileOutputStream fos = new FileOutputStream(pathOutput);
		FileInputStream fis2 = new FileInputStream(pathInput2);
		FileOutputStream fos2 = new FileOutputStream(pathOutput2);
		// 3. 읽어오기
		int data;
		int i = 0;
		
//		while((data = fis.read())!=-1) { // -1 == EOF
//			// 4. 내보내기
//			fos.write(data);
//			i++;
//			System.out.println("파일 복사중... " + i);
//		}
		
		// 속도 향상을 위해 배열 사용
		byte[] arr = new byte[1024];
		while(fis2.read(arr)!=-1) { // -1 == EOF
			// 4. 내보내기
			fos2.write(arr);
			i++;
			System.out.println("파일 복사중... " + i);
		}
		
		System.out.println("복사 완료");
		// 5. flush, close
		fis.close();
		fos.flush();
		fos.close();
		fis2.close();
		fos2.flush();
		fos2.close();
	}

}



다음 예제는 File Reader와 File Writer을 이용한 예제이다.


Writer와 Reader는 문자형 특화로 txt 파일을 만들 때 자주 쓰인다.





package chap11.exam06.charIO;

import java.io.FileReader;

public class TextInput {

	public static void main(String[] args) throws Exception {
		// 1. 파일 위치 지정
		String path = "C:/img/asd.txt";
		// 2. 스트림 준비
		FileReader fr = new FileReader(path);
		// 3. 읽어오기
		char[] arr = new char[100];
		
		while(fr.read(arr)!=-1) { // -1 == EOF
			String data = new String(arr);
			// 4. 출력하기
			System.out.println(data);
			// System.out.print(arr);
		}

		
		// 5. 자원닫기
		
	}

}


package chap11.exam06.charIO;

import java.io.FileWriter;

public class TextOutput {

	public static void main(String[] args) throws Exception {
		// 1. 파일 위치 설정
		String fileName = "C:/img/temp/write.txt";
		// 2. 스트림 준비
		// append 인자 - 이어쓰기 여부
		FileWriter fw = new FileWriter(fileName, true);
		// 3. 쓰기
		System.out.println("저장 시작");
		fw.write("for 문 시작 \r\n");
		for(int i = 1; i <= 10; i++) {
			fw.write("for 문 증가 : " + i + "\r\n");
		}
		fw.write("for 문 종료\r\n");
		// 4. flush, close
		System.out.println("저장 종료");
		fw.flush();
		fw.close();
		
		// 실행을 두 번 해보면 데이터가 새로 쓰이지 않고 축적된다.
		// append를 true값으로 해서
	}

}


package chap11.exam07.test;

import java.io.FileWriter;
import java.util.Scanner;

public class WriteTest {

	public static void main(String[] args) throws Exception {
		// 1. 파일 위치 설정
		String fileName = "C:/img/temp/testkey.txt";
		
		// 2. 스캐너 준비
		Scanner scan = new Scanner(System.in);
		
		// 3. Writer 준비
		// append 인자 - 이어쓰기 여부
		FileWriter fw = new FileWriter(fileName, true);
		
		// 4. 읽어오기
		String temp = "";
		System.out.println("저장 시작");
		while(true) {
			System.out.println("추가할 문장을 입력하세요.(end test 입력 할 경우 끝남)");
			temp = scan.nextLine();
			if (temp.equals("end test")) { break; }
			else {
				// 5. 내보내기
				fw.write(temp);
				fw.write("\r\n");
				fw.flush();
			}
		}
		
		// 6. 자원 종료
		System.out.println("저장 종료");
		fw.close();
	}

}


+ Recent posts