How to get ddd from the path name where the test.java resides.
File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use
File‘sgetParentFile()method andString.lastIndexOf()to retrieve just the immediate parent directory.Mark’s comment is a better solution than
lastIndexOf():These solutions only works if the file has a parent file (e.g., created via one of the file constructors taking a parent
File). WhengetParentFile()is null you’ll need to resort to usinglastIndexOf, or use something like Apache Commons’FileNameUtils.getFullPath():There are several variants to retain/drop the prefix and trailing separator. You can either use the same
FilenameUtilsclass to grab the name from the result, uselastIndexOf, etc.