window와 Linux os 에서 파일저장할때 다른 os에서 실행할때마다
일일이 바꿔주는건 번거로우니 os를 찾는 메서드를 사용한다.
System.getProperty("os.name")는
Java 시스템 프로퍼티 중 하나로, 현재 운영체제의 이름을 문자열로 반환
이렇게 반환된 운영체제 이름 문자열을 toLowerCase() 메서드로 모두 소문자로 변환한 후,
contains() 메서드로 특정 문자열이 포함되어 있는지 확인
그리고 폴더가 없는 경우 그때그때 만들어주는 메서드를 이용한다.
Files.createDirectories() 메서드는 주어진 경로에 필요한 모든 디렉토리를 생성함.
이 메서드의 특징은 디렉토리가 이미 존재하면 그대로 두고, 없는 경우에만 새로 생성
전체코드
try {
// 파일 저장 경로 설정
Path directoryPath;
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) { // 윈도우인 경우
directoryPath = Paths.get("C:" + File.separator + "폴더이름" + File.separator + filename);
} else { // 리눅스인 경우
directoryPath = Paths.get(File.separator + "home" + File.separator + "폴더이름" + File.separator + "폴더이름" + File.separator + filename);
}
// 디렉토리가 없을 경우 새로운 위에 입력된 디렉토리를 생성하고, 없으면 무시
Files.createDirectories(directoryPath.getParent());
// 파일 복사
Files.copy(file.getInputStream(), directoryPath, StandardCopyOption.REPLACE_EXISTING)
} catch (Exception e) {
e.printStackTrace();
throw new IOException(filename + " 다시 시도해주세요.", e);
}