728x90
파일의 이름과 확장자 분리 / How to get name and extension of a file in java
package test;
public class Test {
public static void main(String[] args) {
String file = "abcdef.pdf";
int lastIndex = file.lastIndexOf(".");
String fileName = file.substring(0, lastIndex);
String extension = file.substring(lastIndex + 1);
System.out.println("file name : " + fileName);
System.out.println("file extension : " + extension);
}
}
package test;
import java.util.Optional;
public class Test {
public static void main(String[] args) {
String file = "abcdef.pdf";
Optional<String> fileName = getFileNameByStringHandling(file);
System.out.println("file name : " + fileName.get());
Optional<String> extension = getExtensionByStringHandling(file);
System.out.println("file extension : " + extension.get());
}
public static Optional<String> getFileNameByStringHandling(String filename) {
return Optional.ofNullable(filename).filter(f -> f.contains("."))
.map(f -> f.substring(0, filename.lastIndexOf(".")));
}
public static Optional<String> getExtensionByStringHandling(String filename) {
return Optional.ofNullable(filename).filter(f -> f.contains("."))
.map(f -> f.substring(filename.lastIndexOf(".") + 1));
}
}
728x90
댓글