운영 체제 간의 호한성 유지를 위한 "/"의 사용
-> 경로 문자열을 설정할 때 윈도우 기반에서는 역슬래시()를 사용하지만 이 경우 이스케이프 문자를 사용하 여 '\'의 형식으로 사용해야 하고, 가급적 다른 운영체제와의 호환성을 위해 슬래시(/)를 사용하는 것이 좋음
절대 경로
: 작업 디렉토리와 관계없이 절대적인 위치를 의미하는 경로
-> 리눅스 : /etc/httpd/conf/httpd.conf
-> 윈도우 : C:/Windows/System32/divers/etc/hosts
상대 경로
: 작업 디렉토리를 기준으로 상대적인 위치를 의미하는 경로
-> 리눅스 : ./(내 폴더에서 이동, 없어도 됨)conf/httpd,conf
-> 윈도우 : ../(내 상위 폴더로 이동)/divers/etc/hosts
package file;
import java.io.File;
public class Main01 {
public static void main(String[] args) {
File file = new File("src/file/Main01.java");
// 전달된 경로가 파일인지를 검사 -> 존재하지 않은 파일로 검사할 경우 무조건 false
boolean is_file = file.isFile();
System.out.println("is_file : " + is_file);
// 전달된 경로가 디렉토리인지 검사 -> 존재하지 않는 디렉토리로 검사할 경우 무조건 false
boolean is_dir = file.isDirectory();
System.out.println("is_dir : " + is_dir);
// 전달된 경로가 숨긴 형태인지 검사 -> 존재하지 않는 파일로 검사할 경우 무조건 false
boolean is_hidden = file.isHidden();
System.out.println("is_hidden : " + is_hidden);
// 절대 경로 값을 추출
String abs = file.getAbsolutePath();
System.out.println("절대 경로 : " + abs);
// 생성자에 전달도니 파일이나 디렉토리가 물리적으로 존재하는지를 검사
boolean is_exist = file.exists();
System.out.println("존재 여부 : " + is_exist);
System.out.println("----------------------------------------------------------------");
// 디렉토리 정보 객체 생성
File file2 = new File("a/b/c/target");
System.out.println("is File : "+file2.isFile());
System.out.println("is Directory : "+file2.isDirectory());
System.out.println("is hidden : "+ file2.isHidden());
System.out.println("절대 경로 : "+file2.getAbsolutePath());
System.out.println("존재 여부 : "+file2.exists());
// 경로에 따른 디렉토리 생성
file2.mkdirs();
System.out.println("----------------------------------------------------------------");
// 마지막 "/" 이후 단어를 리턴
System.out.println(file.getName());
System.out.println(file2.getName());
// 처음부처 마지막 "/" 직전까지 리턴
System.out.println(file.getParent());
System.out.println(file2.getParent());
}
}
: 문자나 기호들의 집합을 컴퓨터에서 저장하거나 통신에 사용할 목적으로 부호화하는 방법
: 입출력에서 stream이란 디바이스의 입출력 방식이character 단위이던 block 단위이던 관계없이 1바이트씩 연속적으로 전달되는 형태로, 추상화된 상태를 의미
package file;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
public class Main02 {
public static void main(String[] args) {
// 저장할 파일의 경로
final String PATH = "./text.txt";
// 파일에 저장할 내용
String write_string = "가나다라마바사abcdefg";
// 특정 인코딩 방식 적용
// getBytes() 메서드는 존재하지 않는 인코딩 형식에 대한 지정을 방지하기 위해서
// 예외처리를 강제적으로 요구
// 변수의 유효성 범위가 서로 달라서 buffer를 인식하지 못하는 문제 발생
byte[] buffer = null;
try {
buffer = write_string.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// finally 블록에서 인식하기 위해서 선언부를 위로 이동
OutputStream out = null;
// 파일 저장 절차 시작
try {
out = new FileOutputStream(PATH);
// 파일 쓰기
out.write(buffer);
System.out.println("[INFO] 파일 저장 성공 >> "+PATH);
} catch (FileNotFoundException e) {
System.out.println("[ERROR] 지정된 경로를 찾을 수 없음 >> "+PATH);
e.printStackTrace();
} catch (IOException e) {
System.out.println("[ERROR] 파일 저장 실패 >> "+PATH);
e.printStackTrace();
} catch (Exception e) {
System.out.println("[ERROR] 알 수 없는 에러 >> "+PATH);
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package file;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class main03 {
public static void main(String[] args) {
// 읽을 파일의 경로
final String PATH = "./text.txt";
// 읽은 내용이 담겨질 스트림
byte[] data = null;
// 읽은 내용이 담겨질 스트림
String read_string = null;
// 파일 읽기
InputStream in = null;
try {
in = new FileInputStream(PATH);
// 읽은 내용을 담기 위한 배열은 파일의 용량만큼 사이즈를 할당 int.available() ->열고 있는 파일의 크기
data = new byte[in.available()];
// 파일 읽기 - 파라미터로 전달된 배열 안에, 패일 내용을 담아줌
in.read(data);
System.out.println("[INFO] 파일 읽기 성공 >> " + PATH);
} catch (FileNotFoundException e) {
System.out.println("[ERROR] 지정된 경로를 찾을 수 없음 >> " + PATH);
e.printStackTrace();
} catch (IOException e) {
System.out.println("[ERROR] 파일 읽기 실패 >> " + PATH);
e.printStackTrace();
} catch (Exception e) {
System.out.println("[ERROR] 알 수 없는 에러 >> " + PATH);
e.printStackTrace();
}
finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// data 배열에 내용이 있다면, 문자열로 변환하여 출력
if(data != null) {
try {
read_string = new String(data, "utf-8");
System.out.println(read_string);
} catch (UnsupportedEncodingException e) {
System.out.println("[ERROR] 인코딩 지정 에러");
e.printStackTrace();
}
}
}
}