I’m trying to print a folder name where a file is stored.
Example:
I have the file picture.jpg
Stored in the path C:\Users\Desktop\Foldername\picture.jpg
Is it possible to print “Foldername”. I’ve tried a substring but that seems to rely on me hard-coding the character number in. EG:
System.out.println(path.substring(33, 38));
If my program was to be released, and the user had a different file path – this would offset the substring.
To select the file, my program has the following code
chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File(computerUsername+"\\Desktop\\Foldername"));
chooser.setDialogTitle(choosertitle);
chooser.setAcceptAllFileFilterUsed(true);
Therefore, the below code prints out a nullpointexpection error.
chooser.getPath().getName();
What you need is
java.io.File. It has methods to transform paths.If you didn’t have that, the way to do it “by hand” would be to look for path separator characters (
\) and split around those.