JAVA에서는 File 클래스를 사용하여 파일과 디렉토리를 생성할 수 있다.
개발자들이 자주 사용하는 Object는 아니라 생각된다.
보통 파일업로드, 다운로드, 엑셀 다운로드와 같은 공통 기능들에 사용되기 때문에 Util로 한번 개발해 놓으면 해당 메소드를 콜 해서 사용하는 정도가 대부분일 것이다.
File Object에 대해 코드를 분석할 수 있을정도로만 알아보도록 하자.
String rootPath = "C:/DevLog/";
String sFilePath = rootPath + "test.txt";
File file = new File(sFilePath);
file.createNewFile();
실무에 적용할 때 rootPath는 설정값을 읽어서 사용하도록 한다.
properties파일 또는 yml 파일의 값은 서버와 분리하여 사용하기 때문이다.
(Build시 해당 파일을 제외한다던가 설정을 통해 Local, 개발서버, 운영서버 설정 파일을 분리)
String rootPath = "C:/DevLog/";
String sNewDirectory = rootPath + "study";
File file = new File(sNewDirectory);
file.mkdir();
String rootPath = "C:/DevLog/";
//생성일자, 파일명
Calendar cal = Calendar.getInstance() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat timeForamt = new SimpleDateFormat("yyyyMMddhhssSSS");
String date = dateFormat.format(cal.getTime());
String serial = timeForamt.format(cal.getTime());
String sDirectoryPath = String.format("%s%s", rootPath, date);
String sFilePath = String.format("%s/devlog_%s.txt", sDirectoryPath, serial);
File directory = new File(sDirectoryPath);//디렉토리 경로
File file = new File(sFilePath); //파일 경로
// 디렉토리 존재여부 체크
if(!directory.exists()) {
directory.mkdir(); // 디렉토리 생성
System.out.println("디렉토리 생성");
}else {
System.out.println("디렉토리 존재");
}
file.createNewFile(); // 파일 생성
일자별 폴더에 파일을 생성한다고 가정했다. 해당 일자에 최초 한 번만 폴더를 생성하면 된다. exists 메소드를 사용하여 존재여부를 체크하고 일자 폴더를 생성하였다.
파일명 또한 시간값을 이용하여 뒤에 suffix를 생성하여 만들었다. 파일 업로드, 다운로드 모두 어떤 파일명이 올지 모른다. 사용자가 요청한 파일명을 그대로 사용하여 서버에 저장한다면 이미 생성되어 있는 파일이 존재할 수 있다.
그렇기 때문에 업로드 할 경우 실제 파일명에 일련번호(시간값)를 붙여서 저장하거나 일련번호로 바꿔서 저장하는 것이 보통이다.
DB에는 실제 파일명과 물리적 파일명을 함께 저장하기 때문에 다운로드 할때 물리적 파일명을 찾아 다운로드한다.
File file = new File("C:/DevLog/devlog.txt"); //original File
File renameFile = new File("C:/DevLog/rename.txt"); //new File
file.renameTo(renameFile);
변경 전
변경 후
File file = new File("C:/DevLog/devlog.txt"); //original File
file.delete();
파일 복사를 위해 사용하는 객체이다.
String rootPath = "C:/DevLog/";
String fileName = "devlog";
//생성일자
Calendar cal = Calendar.getInstance();
SimpleDateFormat timeForamt = new SimpleDateFormat("yyyyMMddhhssSSS");
String serial = timeForamt.format(cal.getTime());
File file = new File(String.format("%s%s.txt", rootPath, fileName)); //download target file
File newFile = new File(String.format("%s%s_%s.txt", rootPath, fileName, serial)); //download file
FileCopyUtils.copy(file, newFile);
복사 전
복사 후
[JAVA] Custom Annotation 생성 및 활용 (5) | 2023.03.05 |
---|---|
[JAVA] Calendar (날짜와 시간) 내일, 월말, 월초, 년말, 년초, 윤년 구하기 (4) | 2023.02.19 |
JAVA 업캐스팅, 다운캐스팅, instanceof 연산자 (0) | 2022.10.17 |
[JAVA] Comparable과 Comparator (0) | 2022.07.19 |
[JAVA] SortedMap - TreeMap 사용법 (0) | 2022.07.18 |
댓글 영역