어려울 거 같아서 미뤄뒀던 프로그래밍 공부 이번에 숨 딱 참고 Java 다이브 💦
//C:\photo\food.jpg 파일에 대한 객체 생성
File file = new File("C:\photo\food.jpg");
File file = new File("C:\photo", "food.jpg");
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);
// 경로에 따른 디렉토리 생성
file.mkdirs(); // make directorys
System.out.println(file.getName());
System.out.println(file.getParent());
// 성공시 true, 실패 시 false
boolean del_ok = file.delete();
System.out.println("delete ok : " + del_ok);
운영체제간의 호환성 유지를 위한 "/" 의 사용
- 경로 문자열을 설정할 때 윈도우 기반에서는 역슬래시( \ )를 사용하지만, 이 경우 이스케이프문자를 사용하여 "\ \"의 형식으로 사용해야 하고, 가급적 다른 운영체제와의 호환성을 위해 슬래시( / )를 사용하는 것이 좋아요.
리눅스 : /etc/httpd/conf/httpd/conf
윈도우 : C:/Windows/System32/drivers/etc/hosts
리눅스 : ./conf/httpd/conf
윈도우 : ../drivers/etc/hosts
예) 모스부호, UTF-8(8비트 이진수로 표현하는 방법)
스트림 관련 클래스들을 각각 InputStream(입력/읽기), OutputStream(출력/저장)과 관련된 인터페이스를 상속받기 때문에 모두 동일한 메서드를 가지고 있어요.
public class Main02 {
public static void main(String[] args) {
// 저장할 파일의 경로
String path = "text.txt";
// 파일에 저장할 내용
String write_string = "가나다라마바사abcdefg";
// 특정 인고딩 방식 적용
// 객체나 배열이 선언과 할당에 대한 블록이 서로 분리되어 있을 경우
// 명시적으로 빈 영역임을 알리기 위하여 null로 초기화
byte[] buffer = null;
try {
buffer = write_string.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
System.out.println("[ERROR] 알 수 없는 인코딩 정보 >> " + path);
e.printStackTrace();
} catch(Exception e) {
System.out.println("[ERROR] 알 수 없는 에러 >> " + path);
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();
}
}
}
}
public class Main03 {
public static void main(String[] args) {
// 읽을 파일 경로
String path = "text.txt";
// 읽은 내용이 담겨질 스트림
byte[] data = null;
// 읽은 내용이 변환될 문자열
String read_string = null;
// 파일 읽기
InputStream in = null;
try {
in = new FileInputStream(path);
// 읽은 내용을 다믹 위한 배열은 파일의 용량만큼 사이즈를 할당한다.
// in.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 {
if( in != null ) {
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();
}
}
}
}
다음 다이브에서 또 만나요 🌊
출처
https://media.giphy.com/media/l2Je1bFuOpkNpyqYM/giphy.gif
https://media.giphy.com/media/Jbb3KS22397YQ/giphy.gif