File file = new File("C:\phto\food.jpg");
File file = new File("C:\phto","food.jpg");
package file;
import java.io.File;
public class Main01 {
public static void main(String[] args) {
// File클래스는 절대 경로나, 상대 경로를 생성자 파라미터로 전달
// 이클립스에서 상대 경로를 사용할 경우, 현재 프로젝트가 기준
// Workspace가 C:/java 이고, 프로젝트가 'day20'인 경우의 작업 위치는
// C:/java/day20
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_hiiden : " + 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("isFile : " + file2.isFile());
System.out.println("isDirectory : " + file2.isDirectory());
System.out.println("isHidden : " + 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());
// 삭제 시도 -> 성공시 true, 실패시 false
boolean del_ok = file2.delete();
System.out.println("삭제 성공여부 : " + del_ok);
System.out.println("삭제 성공여부 : ");
}
}
결과
is_file : true
is_dir : false
is_hiiden : false
절대경로 : D:\0803_gb_chs\java\workspace\day13\src\file\Main01.java
존재여부: true
-----------------------------
isFile : false
isDirectory : false
isHidden : false
절대경로 : D:\0803_gb_chs\java\workspace\day13\a\b\c\target
존재여부 : false
-----------------------------
Main01.java
target
src\file
a\b\c
삭제 성공여부 : true
입력 스트림 비교
- 입력 스트림은 데이터를 먼저 스트림으로 읽어 들인다. 그리고 스트림에 존재하는 데이터를 하나씩 일거 들일 수 있다.
- 음료수를 마실 때 빨대를 이용하여 음료수를 빨대에 모으고 빨대에 들어있는 음료수를 흡입한다. 그러면 음료수가 입안으로 들어 올 것이다.
출력 스트림 비교
- 출력 스트림으로 데이터를 보낸다. 출력 스트림에 보낸 데이터를 비워 버린다. 그렇게 되면 출력 스트림에 존재하던 데이터가 모두 목표지점에 저장된다.
- 입 안에 있던 음료수를 빨대로 일단 보낸다. 빨대에 들어있는 음료수를 불어 버린다. 그렇게 되면 음료수는 다시 컵 안으로 들어가게 된다.
출처: https://elena90.tistory.com/entry/Java-파일-입출력스트림InputStreamOutputStreamReaderWriter
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) {
/*
* 문자열을 파일로 저장
* -> 문자열을 파일로 저장하기 위해서는 byte배열로 변환해야 한다.
* -> 문자열을 byte배열로 변환하기 위해서는 getBytes() 메서드를 사용하는데,
* 이 때 변환 과정에서 사용할 인코딩 형식을 지정해 주어야 한다.
*/
// 저장할 파일의 경로
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();
}
// 파일 저장 절차 시작
// 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();
}
}
}
}
결과
[INFO]파일 저장 성공 >>text.txt
package file;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class Main03 {
public static void main(String[] args) {
// 읽을 파일 경로
String path = "text.txt";
byte[] data = 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);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// data 배열에 내용이 있다면, 문자열로 변환하여 출력
if( data != null) {
try {
read_string =new String(data,"utf-8");
} catch (UnsupportedEncodingException e) {
System.out.println("[ERROR] 인코딩 지정 에러");
e.printStackTrace();
}
}
}
}
결과
[INFO] 파일 읽기 성공 >> text.txt