Java & Kotlin

[Java 기능] 그외 여러가지 입출력 클래스들

Sue 2022. 2. 17. 18:34

File 클래스

  • 파일 개념을 추상화한 클래스
  • 입출력 기능(read, write)은 없고, 파일의 이름, 경로, 읽기 전용 여부 등의 속성을 알 수 있음

 

FileTest.java
  • File 생성자 매개변수로 파일의 경로 또는 파일의 이름 입력
  • 출력 스트림과 달리 createNewFile() 메서드를 이용해야 파일이 생성됨
package ch18;

import java.io.File;
import java.io.IOException;

public class FileTest {

	public static void main(String[] args) throws IOException {

		File file = new File("D:\\suea7\\Documents\\newFile.txt");	// 경로 지정
		file.createNewFile();	// 파일 생성
		
		System.out.println(file.isFile());
		System.out.println(file.isDirectory());
		System.out.println(file.getName());
		System.out.println(file.getAbsolutePath());
		System.out.println(file.getPath());
		System.out.println(file.canRead());
		System.out.println(file.canWrite());
		
		file.delete();	// 파일 제거
	}
}

 

수행 결과
true
false
newFile.txt
D:\suea7\Documents\newFile.txt
D:\suea7\Documents\newFile.txt
true
true

 


RandomAccess 클래스

  • 입출력 클래스 중 유일하게 입력과 출력을 동시에 할 수 있는 클래스 (스트림은 아님)
  • 파일 포인터가 있어서 읽고 쓰는 위치의 이동이 가능함
  • 파일에서 간단한 데이터를 읽어들일때 스트림을 여는 것보다 편리할 수 있음

 

RandomAccessFileTest.java
  • seek() 메서드로 파일 포인터를 원하는 위치로 이동할 수 있음
  • write와 read 메서드는 같은 순서로 사용해야 함
package ch18;

import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileTest {

	public static void main(String[] args) throws IOException {
		
		RandomAccessFile rf = new RandomAccessFile("random.txt", "rw");
		
		rf.writeInt(100);
		System.out.println("pos : " + rf.getFilePointer());
		rf.writeDouble(3.14);
		System.out.println("pos : " + rf.getFilePointer());
		rf.writeUTF("안녕하세요");	// 3byte로 저장, String 끝에는 null 문자 붙음
		System.out.println("pos : " + rf.getFilePointer());
		
		rf.seek(0);	// 파일 포인터를 맨 처음 위치로 이동
		
		int i = rf.readInt();
		double d = rf.readDouble();
		String s = rf.readUTF();
		
		System.out.println(i);
		System.out.println(d);
		System.out.println(s);
		
	}

}

 

수행 결과
pos : 4		// int 4byte
pos : 12	// double 8byte
pos : 29	// 한글 각 3byte씩 + null char
100
3.14
안녕하세요