1. File 클래스
- java.io.File 클래스는 파일의 크기, 파일의 접근권한, 파일의 삭제, 이름 변경등의 작업을 할 수 있는 기능을 제공한다.
- 이때, 디렉토리(폴더) 역시 파일로써 취급된다는 것이다.
1-1. File 클래스 생성자
- File(File parent, String child) - parent 디렉토리에 child라는 파일에 대한 File 객체를 생성한다.
- File(String child) - child라는 파일에 대한 File 객체를 생성한다.
- File(String parent, String child) - parent 디렉토리에 child라는 파일에 대한 File 객체를 생성한다.
* File 인스턴스를 생성했다고 실제 폴더에 파일이 생성되는것은 아니고 메모리 상에 생성된다.
1-2.File 클래스의 중요 메소드
- boolean canRead() - 파일이 읽기 가능한 경우 true, 그렇지 않은 경우 false를 반환한다.
- boolean canWrite() - 파일이 쓰기 가능한 경우 true, 그렇지 않은 경우 false를 반환한다.
- boolean createNewFile() - 지정한 파일이 존재하지 않은 경우 파일을 생성한다.
- boolean delete() - 파일을 삭제한다. 디렉토리인 경우 비어있으면 삭제한다.
- void deleteOnExit() - JVM이 종료될때, 파일을 삭제한다.
- boolean exists() - 파일이 존재할 경우 true, 그렇지 않을 경우 false를 반환한다.
2. 예제
2-1. 파일 정보 예제
import java.io.File;
import java.io.IOException;
public class _02_FileInfo {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("사용법: java FileInfo 파일 이름");
System.exit(0);
} //if end
File f = new File(args[0]);
if(f.exists()) { //파일이 존재하는 경우
System.out.println("length: " + f.length());
System.out.println("canRead: " + f.canRead());
System.out.println("canWrite: " + f.canWrite());
System.out.println("getAbolutePath: " + f.getAbsolutePath());
try{
System.out.println("getCanonicalPath: " + f.getCanonicalPath());
}catch (IOException ioEx) {
System.out.println(ioEx);
}
System.out.println("getName: " + f.getName());
System.out.println("getParent: " + f.getParent());
System.out.println("getPath: " + f.getPath());
}else { //파일이 존재 하지 않을우경우
System.out.println("파일이 존재하지 않습니다.");
}
}
}
2-2. 파일삭제 예제
import java.io.*;
public class _03_FileDelete {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("사용법: java FileDelete 파일이름");
System.exit(0);
}
File f = new File(args[0]);
if (f.exists()) {
boolean deleteFlag = f.delete();
if (deleteFlag) {
System.out.println("파일이 삭제되었습니다.");
} else {
System.out.println("파일 삭제가 실패햐였습니다.");
}
} else {
System.out.println("파일이 존재하지 않습니다.");
}
}
}
2-3. File 클래스를 이용한 임시파일 생성과 삭제
import java.io.*;
public class _04_TempFile {
//윈도우: c:/temp
//맥: /tmp
//프로그램이 실행되는 동안만 필요한 파일
//프로그램 실행 -> 생성, 프로그램 종료 -> 삭제
public static void main(String[] args) {
try {
File f = File.createTempFile("tmp_", ".dat");
System.out.println(f.getAbsolutePath());
System.out.println("5초 동안 멈춰있습니다.");
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
System.out.println(e1);
}
f.deleteOnExit(); //JVM이 종료될떄 자동으로 파일이 삭제된다.
}catch (IOException e) {
System.out.println(e);
}
}
}
3. InputStream, OutputStream
- InputStream, OutputStream은 추상클래스이다
- byte 단위 입출력 클래스는 InputStream, OutputStream의 자식클래스이다
Byte Stream
3-1. InputStream, OutputStream이 가지는 중요 메소드
- int available() throws IOException - 현재 읽을 수 있는 바이트 수를 반환한다.
- void close() throws IOException - 입력 스트림을 닫는다.
- int read() throws IOException - 입력 스트림에서 한 바이트를 읽어서 int값으로 반환한다. 더이상 읽어들일 내용이 없을때(EOF)는 -1을 반환한다.
- int read(byte buf[]) throws IOException - 입력 스트림에서 buf[] 크기만큼을 읽어 buf에 저장하고 읽은 바이트수를 반환한다. 더이상 읽어들일 내용이 없을때(EOF)는 -1을 반환한다.
- int skip(long numBytes) throws IOException - numBytes로 지정된 바이트를 무시하고, 무시된 바이트수를 반환한다.
3-2. 예제
import java.io.IOException;
import java.io.InputStream;
/*
1byte가 표현할 수 있는 값: 00000000 ~ 11111111
read()메소드가 읽어 들일수 있는 정 = 00000000 ~ 11111111중의 1개
1byte씩 파일을 읽어들인다 -> 100byte면 100번 읽어들여야함
1byte씩 읽어들이는데 파일의 크기를 모른다. 언재까지 읽어 들이냐?
더이상 읽어들일 것이 없을떄까지 -> EOF(EndOfFile)
그럼 EOF는 어떻게 표현할 것이냐? -> 1byte씩 읽어들이기는 하지만 아에 그릇을 크게 만들자
int(4byte)에 1byte값을 담자 -> 00000000 00000000 00000000 00000000
00000000 00000000 00000000 11111111
EOF: -1
1 --> 00000000 00000000 00000000 00000001
1의 보수 -> 11111111 11111111 11111111 11111110
2의 보수 -> 11111111 11111111 11111111 11111111: -1
*/
public class _05_InputStreamExam {
public static void main(String[] args) {
InputStream in = null;
try {
int data = in.read(); //왜 byte단위로 읽어들이는 read메소드가 int값을 반환하나? -> byte 단위로는 EOF를 표현할 수 없기 떄문에
}catch (IOException ex) {
System.out.println("IOException: " + ex);
}finally {
try {
in.close();
}catch (Exception ex2) {
System.out.println("Exception: " + ex2);
}
}
}
}
'Java > 기초' 카테고리의 다른 글
[Java] JavaIO - (4) Object IO Stream(+깊은복사, 얕은복사) (0) | 2023.10.27 |
---|---|
[Java] JavaIO - (3)Data, ByteArray, StringReaderWriter (0) | 2023.10.27 |
[Java] JavaIO - (1) (0) | 2023.10.25 |
[Java] 상속 - 필드, 메서드 오버라이딩할 때 주의점 (0) | 2023.10.23 |
[Java]자바 프로그램의 실행 과정 (0) | 2023.10.21 |