English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 예제에서는 Java의 절대 경로에서 파일 이름을 가져오는 방법을 배웁니다.
import java.io.File; class Main { public static void main(String[] args) { //Test.class 파일에 연결됩니다 File file = new File("C:\\Users\\Bhandari\\Desktop\\w3codebox\\Java Article\\Test.class"); //getName()로 파일 이름 가져오기 String fileName = file.getName(); System.out.println("파일 이름: " + fileName); } }
출력 결과
파일 이름: Test.class
위의 예제에서는 File 클래스의 getName() 메서드를 사용하여 파일 이름을 가져왔습니다.
더 많은 파일에 대한 정보를 알고 싶다면 방문하세요Java File。
파일의 절대 경로에서 파일 이름을 가져올 수 있는 문자열 메서드를 사용할 수 있습니다.
import java.io.File; class Main { public static void main(String[] args) { File file = new File("C:\\Users\\Bhandari\\Desktop\\w3codebox\\Java Article\\Test.class"); //파일을 문자열로 변환합니다. String stringFile = file.toString(); int index = stringFile.lastIndexOf('\\'); if(index > 0) { String fileName = stringFile.substring(index + 1); System.out.println("파일 이름: " + fileName); } } }
출력 결과
파일 이름: Test.class
위의 예제에서
file.toString() - File 객체를 문자열로 변환합니다。
stringFile.lastIndexOf() -stringFile에서 문자'\\'의 마지막 위치를 반환합니다. 더 알고 싶다면 방문해 주세요Java String lastIndexOf()。
stringFile.substring(index +1) - 위치 반환index +1이후의 모든 서브 문자열을 더 알고 싶다면 방문해 주세요Java String substring()。