0

I have been looking for an answer to this question, but haven't found any solutions.

Basically, I am trying to print ONLY the Working Directory under which the file in question is. Eg. if the file is in "C:\Users\user\Desktop\folder", I would want it to print out only "folder".

Is there any way to do this avoiding trimming the path string?

Here is a section of my code, in case someone needs it.

JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Choose a folder to rename the elements");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);

if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
    out.println("Directory: " + chooser.getSelectedFile());

I am trying to choose a file and print out the folder (not the absolute path) in which it is located.

Any help is much appreciated.

Lorenzo Battilocchi
  • 862
  • 1
  • 10
  • 26
  • _""if the file is in `"C:\Userszuser\Desktopzfolder"`, I would want it to print out only "folder"_ -- Why would you print out `folder`? Shouldn't you print `Desktopzfolder`? – Jim Garrison Dec 21 '17 at 23:30
  • Sorry, yes... I mistyped the "z" was meant to be a backslash. I will correct it now! – Lorenzo Battilocchi Dec 21 '17 at 23:35
  • Possible duplicate of [Java: splitting the filename into a base and extension](https://stackoverflow.com/questions/4545937/java-splitting-the-filename-into-a-base-and-extension) – Andrew Henle Dec 21 '17 at 23:38

1 Answers1

0

@Lorenzo, this works for me. Let me know if any questions.

import org.apache.commons.lang3.StringUtils;

public class Test {
   public static void main(String[] args) {

      String input ="C:\\Users\\user\\Desktop\\folder";

      String[] output = StringUtils.split(input, "\\");

      System.out.println(output[output.length-1]);
    }
}