자바 확장자별 별도 작업 지정하기
자바(JAVA)에서 파일 유형별로 용량을 계산하는 방법입니다, 해당 코드를 활용하면
"파일 확장자별 별도의 작업 지정도 가능합니다."
목적
1. 이미지 파일/ 영상 파일 / 텍스트 파일 들의 파일 형태를 지정하고 각 파일 형별로 나눠서 저장
2. 저장된 파일들의 용량을 모두 모아서 출력하고 싶다
자바 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
public class 파일형별로_용량분할 { public static void main(String[] args) {
String S = "my.song.mp3 11b\n" + "greatSong.flac 1000b\n"
+ "not3.txt 5b\n" + "video.mp4 200b\n" + "game.exe 100b\n"
+ "mov!e.mkv 10000b";
System.out.println(solution(S));
}
public static String solution(String S)
{
//빈값이 없어야 하며 공백제거를 해도 길이가 1이상이여야한다. == 파일명이 존재해야함
if (S != null && S.trim().length() > 1) {
Set<String> music = new HashSet<String>(Arrays.asList("mp3","aac","flac"));
Set<String> images = new HashSet<String>(Arrays.asList("jpg","bmp", "gif"));
Set<String> movies = new HashSet<String>(Arrays.asList("mp4","avi","mkv"));
//파일종류,값으로 생성 전체용량 초기값 =0
//put순서대로 출력해주기 위해 LinkedhashMap로 생성
LinkedHashMap<String, BigInteger> files = new LinkedHashMap<String,BigInteger>();
files.put("music", new BigInteger("0"));
files.put("images", new BigInteger("0"));
files.put("movies", new BigInteger("0"));
files.put("other", new BigInteger("0"));
String[] fileSize = S.split("[\n]");
for (int i = 0; i < fileSize.length; i++) {
//fileSize[i].length() - 1 용량b에서 b의 위치
//fileSize[i].lastIndexOf(".") + 1 확장자가 시작하는 index값
//3. 확장자 용량 (b)제외 형태로 변경
String fileWithSize = fileSize[i].substring(fileSize[i].lastIndexOf(".") + 1,fileSize[i].length() - 1);
//System.out.println(fileWithSize);
//파일명 (공백) 용량 이므로 (공백)을 기준으로 나누기
String[] str = fileWithSize.split("\\s+");
//str[0]->확장자 / str[1] ->용량
if (music.contains(str[0])) {
//music에 포함될경우 music의 값에 새로운값을 추가해주고 해당 값을 music에 put해준다
files.put("music",files.get("music").add(new BigInteger(str[1])));
} else if (images.contains(str[0])) {
files.put("images",files.get("images").add(new BigInteger(str[1])));
} else if (movies.contains(str[0])) {
files.put("movies",files.get("movies").add(new BigInteger(str[1])));
} else {
files.put("other",files.get("other").add(new BigInteger(str[1])));
}
}
//정렬된 files Map에 다시 b를 넣어주고 해당값 return
return returnResult(files);
}
//빈값일경우 null return
return null;
}
private static String returnResult(Map<String, BigInteger> files) {
StringBuilder strBuilder = new StringBuilder();
for (java.util.Map.Entry<String, BigInteger> map : files.entrySet()) {
strBuilder.append(map.getKey() + " " + map.getValue() + "b\n");
}
return strBuilder.toString();
}
}
|
cs |
실행결과
music 1011b images 0b movies 10200b other 105b |
728x90
반응형
'프로그래밍 > Java' 카테고리의 다른 글
[Java / Java 기초 / 자바] Scanner / JOptionPane 로 값 입력하기(JOptionPane 확인창 / 선택창 사용법) (0) | 2023.12.12 |
---|---|
[JAVA / JAVA 기초 / 자바] For-Each란? (0) | 2023.12.12 |
[Springboot(스프링부터)]Entity생성과 JPA설정 (0) | 2022.07.26 |
[Springboot]스프링 부트 시작하기 (0) | 2022.07.11 |
[유즈 케이스]유즈케이스 작성하기 (0) | 2022.07.07 |