java 7 에서 파일 복사, 삭제, 디렉토리 삭제.
private final static CopyOption[] options = new CopyOption[] {
StandardCopyOption.REPLACE_EXISTING, // 복사대상파일이 존재하면 덮어쓰기를 함.
StandardCopyOption.COPY_ATTRIBUTES // 원본파일의 속성까지 모두 복사.
};
// 파일 복사.
private boolean copyFile(String from, String to) {
try {
Path fromFile = Paths.get(from);
Path toFile = Paths.get(to);
if(!toFile.getParent().toFile().exists()) {
toFile.getParent().toFile().mkdirs();
}
Files.copy(fromFile, toFile, options);
logger.info("success : " + from + " >> " + to);
return true;
} catch(Exception e) {
logger.error("Exception : " + from + " >> " + to + ", message : " + e.getMessage());
return false;
}
}
// 파일 삭제.
private boolean deleteFile(String path) {
try {
Path filePath = Paths.get(path);
Files.delete(filePath);
logger.info("success file delete : " + path);
return true;
} catch(Exception e) {
logger.error("Exception delete file : " + path + ", message : " + e.getMessage());
return false;
}
}
// 디렉토리 삭제.
private boolean deleteDir(String path) {
try {
Path dirPath = Paths.get(path);
Files.walkFileTree(dirPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
});
logger.info("success delete : " + path);
return true;
} catch(Exception e) {
logger.error("Exception delete file : " + path + ", message : " + e.getMessage());
return false;
}
}
'프로그래밍 > Java' 카테고리의 다른 글
[이클립스] tptp (1) | 2014.03.24 |
---|---|
spring exception handler (0) | 2014.03.24 |
[MyBatis] null parameter 에러. (0) | 2014.03.19 |
[iBatis/myBatis] #와 $의 차이점 (1) | 2014.01.02 |
[이클립스] generate jaxb classes 한글깨짐. (0) | 2013.09.16 |