How do I create a new directory at the location of an existing file?
I'm fairly new to Java so please forgive me if this is a stupid question.
Basically, a file is a song. I'm using JFileChooser to select multiple songs. I then do some stuff with the array of songs (their file names and paths). I want to then create 2 directories inside the directory in which the songs are located, a directory for the artist name, and a directory for the album name inside the artist name directory. I then want to move the files in my array to the album directory.
I'm fairly sure I'm supposed to be using mkdirs() method.
How can I tell the prog开发者_开发知识库ram to make the directories in the location of the songs whose paths I have stored in an array of files? I can only find examples of getting rid of the extension, not the file name, to be able to use the path for the mkdirs() method.
Suppose you have some File foo
that points to c:\foo\bar\baz\music.wav
, to get the parent directory you can use File.getParentFile()
. I recommend constructing the subdirectories using the File
constructor:
File subdir1 = new File(foo.getParentFile(), "mysubdir1");
if(!subdir1.exists()){
subdir1.mkdirs();
}
Since you're sure that subdir1
's parent exists, you can get away calling subdir1.mkdir()
instead, but you won't lose anything by calling mkdirs
.
I think you're looking for one of the getParent() functions.
精彩评论