I'm trying to get the parent directory of each file and put it into a ListView in Java fx.
It does work, but not for some file names, and I cannot understand why.
Iterator<String> listIterator = loadedFiles.iterator();
StringBuilder listItem = null;
while (listIterator.hasNext()) {
File listFile = new File(listIterator.next());
listItem = new StringBuilder(Arrays.toString(listFile.getAbsolutePath().split(listFile.getName())));
toDir(listItem);
ctrl.fileList.getItems().add(listItem.toString());
}
gets the File Path, and cuts off the filename.
toDir:
private void toDir(StringBuilder builder) {
builder.deleteCharAt(builder.length() - 1);
builder.deleteCharAt(0);
if (builder.charAt(builder.length() - 1) == '\\') {
builder.deleteCharAt(builder.length() - 1);
}
}
Removes the Array brackets and the last '\'
The given file paths are:
C:\Users\Test\Downloads\048815 - Kopie (2).jpg
C:\Users\Test\Downloads\048815 - Kopie (3).jpg
C:\Users\Test\Downloads\048815 - Kopie (4).jpg
C:\Users\Test\Downloads\048815 - Kopie.jpg
C:\Users\Test\Downloads\048815.jpg
The first tree files, the ones with the () in names do not work, the file name is still in the String and added to the list, only the last two ones get the file name removed.
Your immediate problem is that you are misusing String#split()
. The argument to split()
is a regular expression, in which parentheses are grouping meta-characters. You do not want to use split()
at all here. In fact, you are much better off using the path manipulation methods in java.nio.file.Path
.
for (String fileName : loadedFiles)
{
Path filePath = Path.of(fileName);
Path directory = filePath.getParent();
ctrl.fileList.getItems().add(directory.toString());
}
Once you're comfortable with the API, you can reduce this to
for (String fileName : loadedFiles)
{
ctrl.fileList.getItems().add(Path.of(filename).getParent().toString());
}