Java 개념 정리15 (파일 입출력)

김찬미·2023년 4월 5일

Java

목록 보기
20/20

IO(Input, Output) : 입출력과 관련된 스트림

스트림 : 데이터 입출력을 위한 방법. 자바 가상머신에서 콘솔로 값을 보낼 땐 Output, 반대로 콘솔의 값을 JVM에서 읽을 땐 Input

파일 객체를 생성할 경로

String path = "F:\\web1500_KCM\\java\\test.txt";

준비된 경로로 File객체 생성

File f = new File(path);

File 클래스가 생성되면서 path 경로까지 스트림을 생성한다.

System.out.println(f.length() + "byte");
실행 결과 : 9byte

파일의 용량을 알 수 있다. 한글 2byte, 영문, 특수문자는 1byte

파일이든 폴더든 최종 목적지에 해당하는 곳의 용량을 가져올 수 있다.

public class Ex2_File {
	public static void main(String[] args) {
		
		String path = "F:\\web1500_KCM\\java";
		
		File f = new File(path);
		// 파일 클래스의 두 번째 기능
		// 최종목적지가 폴더일 때 해당 폴더가 가진 하위목록의 이름을 가져올 수 있다.
		
		// 폴더 == 디렉토리
		if(f.isDirectory()) {
			String[] names = f.list();
			for (String s : names) {
				System.out.println(s);
			}
		}
		
	}
}
public class Ex3_File {
	public static void main(String[] args) {
		String path = "F:\\web1500_KCM\\java\\aaa\\bbb";
		
		File f = new File(path);
		
		// 파일 클래스는 최종 목적지까지 존재하지 않는 경로가 포함되었는지 판단할 수 있다.
		// exists() : 파일 클래스가 path 경로로 찾아가던 중 정상적으로 폴더나 파일이 존재한다면 true를 반환한다.
		if (!f.exists()) {
			System.out.println("폴더 생성");
			f.mkdirs(); // 폴더를 만들어주는 메서드
		}
		
		// 파일 클래스는 특정 문서를 만들거나, 특정 문서에 들어있는 내용을 읽어오는 것이 불가능하다.
		
		
		
		
	}
}

FileInputStream

File 클래스가 하지 못하는 것들을 FileInputStream이 할 수 있다.

byte 기반의 스트림 -> 1byte씩 읽어온다.

...Stream

char 기반의 스트림 -> 2byte씩 읽어온다.

...Reader,Writer

public class Ex1_FileInputStream {
	public static void main(String[] args) {

		String path = "F:\\web1500_KCM\\java\\test.txt";

		File f = new File(path);

		if (f.exists()) { // 파일이 존재할 때만 수행
			try {
				FileInputStream fis = new FileInputStream(f);
				
				int code = 0;
				// read() 메서드가 한 번에 1byte씩 읽어오다가
				// 더 이상 읽어볼 단어가 없다면 문장의 끝(End Of File)인 -1을 반환한다.
				// 유니코드에도 아스키코드에도 -1에 해당하는 값은 없기 때문에 -1로 정함.
				
				while((code = fis.read()) != -1) {;
					System.out.print((char)code);
				}
				
				// 스트림은 사용이 완료된 후 close를 통해 닫아주는 것이 좋다.
				// 그래야 다음 작업을 하는데 문제가 생기지 않는다.
				// close를 작성하지 않았을 때, 아직 할 작업이 남았으니까 화면에 띄우거나
				// 파일을 만들면 안되겠구나~ 하고 착각하는 경우가 있다.
				
				fis.close();
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}

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

public class Ex2_FileInputStream {
	public static void main(String[] args) {
		String path = "F:\\web1500_KCM\\java\\test.txt";

		File f = new File(path);

		// 배열은 int 범위까지만 만들 수 있다.
		byte[] read = new byte[(int) f.length()];

		// 배열의 크기를 딱 맞춰서 메모리 낭비를 하지 않는게 가장 좋지만, 상황에 따라 다른 파일을 받는다면 용량을 알 수가 없다.

		if (f.exists()) {
			try {
				FileInputStream fis = new FileInputStream(f);

				fis.read(read);

				String res = new String(read);

				System.out.println(res);

				fis.close();

			} catch (Exception e) {
				// TODO: handle exception
			}

		}

	}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class Ex3_FileInputStream {
	public static void main(String[] args) {
//		String path = "F:\\web1500_KCM\\java\\test.txt";
//		File f = new File(path);

		byte[] keyboard = new byte[100];

		try {
			System.out.print("값 : ");
			// 표준입력장치 스트림
			System.in.read(keyboard);

			String s = new String(keyboard);
			System.out.println(s);

			Scanner sc = new Scanner(System.in);
			String res = sc.next();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;

public class Ex4_FileInputStream {
	// 임의의 경로에 file.txt 문서를 만들고
	// 아무 내용이나 문장을 입력해둔다.
	// file.txt의 내용을 FileInputStream으로 읽어온 뒤,
	// 이 값이 회문인지 아닌지를 판별하세요.

	public static void main(String[] args) {
		String path = "F:\\web1500_KCM\\java\\file.txt";

		File f = new File(path);

		byte[] read = new byte[(int) f.length()];

		if (f.exists()) {
			try {
				FileInputStream fis = new FileInputStream(f);
				fis.read(read);

				String ori = new String(read);
				String rev = "";

				for (int i = ori.length() - 1; i >= 0; i--) {
					rev += ori.charAt(i);
				}

				if (ori.equals(rev)) {
					System.out.println(ori + "는 회문입니다.");
				} else {
					System.out.println(ori + "는 회문이 아닙니다.");
				}

				fis.close();

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
import java.io.IOException;
import java.io.PrintStream;

public class Ex1_PrintStream {
	public static void main(String[] args) {

		// 화면에 데이터를 출력하도록 하는 대표적인 클래스
		PrintStream ps = System.out;

		ps.write('A');
		ps.write('B');
		ps.write('\n');
		ps.write('C');

		System.out.println();

		try {
			byte[] by = { 'J', 'A', 'V', 'A' };
			ps.write(by);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		ps.close();

	}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Ex2_FileOutputStream {
	public static void main(String[] args) {

		try {
			FileOutputStream fos = new FileOutputStream("F:\\web1500_KCM\\java\\fileOut.txt", true);

			fos.write('f');
			fos.write('i');
			fos.write('l');
			fos.write('e');
			fos.write('\n');

			String msg = "fileOutput예제입니다.\n";
			String msg2 = "여러줄도 가능\n";

			// getBytes() : 문자열을 byte[] 배열로 반환하는 메서드
			fos.write(msg.getBytes());
			fos.write(msg2.getBytes());

			fos.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
profile
백엔드 지망 학부생

0개의 댓글