Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

여러가지 입출력 클래스 본문

Java/다양한 기능

여러가지 입출력 클래스

Seung__ 2021. 10. 31. 23:36

1. File 클래스

  • 파일 개념을 추상화한 클래스
  • 입출력 기능은 없고, 파일의 이름, 경로, 읽기 전용등의 속성을 알 수 있음.
  • 이를 지원하는 여러 메서드들이 제공됨.
  • createNewFile() 메서드를 통해 파일 생성 가능
public class FileTest {

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

        File file = new File("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();
    }

}

 

 

2. RandomAccessFile 클래스

  • 입출력 클래스 중 유일하게 파일에 대한 입력과 출력을 동시에 할 수 있는 클래스
  • 파일 포인터가 있어서 읽고 쓰는 위치의 이동이 가능함
  • 다양한 메서드 제공됨.
public class AccessRandomFileTest {

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

        RandomAccessFile rf = new RandomAccessFile("random.txt", "rw");
        rf.writeInt(100); //int : 4byte
        System.out.println("파일 포인터 위치:" + rf.getFilePointer());
        rf.writeDouble(3.14); // double : 8byte -> 4+8
        System.out.println("파일 포인터 위치:" + rf.getFilePointer());
        rf.writeUTF("안녕하세요"); //한글 : 3byte(modified uft-8) -> 4+8+15+2(new line)
        System.out.println("파일 포인터 위치:" + rf.getFilePointer());

        rf.seek(0); //맨 앞으로 이동
        System.out.println("파일 포인터 위치:" + rf.getFilePointer());

        int i = rf.readInt();
        double d = rf.readDouble();
        String str = rf.readUTF();

        System.out.println("파일 포인터 위치:" + rf.getFilePointer());
        System.out.println(i);
        System.out.println(d);
        System.out.println(str);
    }

}
파일 포인터 위치:4
파일 포인터 위치:12
파일 포인터 위치:29
파일 포인터 위치:0
파일 포인터 위치:29
100
3.14
안녕하세요

 

 

3. GitHub : 211031 File class, RandomAccessFile


 

GitHub - bsh6463/various_functions

Contribute to bsh6463/various_functions development by creating an account on GitHub.

github.com

 

'Java > 다양한 기능' 카테고리의 다른 글

Thread  (0) 2021.11.01
Decorator Pattern 예제  (0) 2021.11.01
DataInput(Output)Stream, Serialization(직렬화)  (0) 2021.10.31
보조 스트림  (0) 2021.10.31
문자단위 입출력 스트림  (0) 2021.10.31
Comments