Why not just use it File.mkdirs()?
edit: for your requirement not to use File.mkdirs ():
It’s still easier for me to use Fileas a helper class:
package com.example.test;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
public class FileSplitter {
final private File path;
public List<String> getPathStrings()
{
LinkedList<String> list = new LinkedList<String>();
File p = this.path;
while (p != null)
{
list.addFirst(p.getPath());
p = p.getParentFile();
}
return list;
}
public FileSplitter(File path) { this.path = path; }
public static void main(String[] args) {
doit(new File("/foo/bar/baz"));
doit(new File("/bam/biff/boom/pow"));
}
private static void doit(File file) {
for (String s : new FileSplitter(file)
.getPathStrings())
System.out.println(s);
}
}
On my machine (windows) this produces:
\
\foo
\foo\bar
\foo\bar\baz
\
\bam
\bam\biff
\bam\biff\boom
\bam\biff\boom\pow
If you need to use slashes, no matter what I do, I would either use strings, not files, or just use .replace('\\','/').
Finally, here is an approach that might be more useful for your final application.
, ,
mkdir() -Runnable, :
package com.example.test;
import java.io.File;
public class PathRunner
{
final private File path;
public PathRunner(File path) {
this.path = path;
}
public interface Step
{
public boolean step(File path);
}
public boolean run(Step step)
{
return run(step, this.path);
}
private boolean run(Step step, File p)
{
if (p == null)
return true;
else if (!run(step, p.getParentFile()))
return false;
else
return step.step(p);
}
public static void main(String[] args) {
doit(new File("/foo/bar/baz"));
doit(new File("/bam/biff/boom/pow"));
}
private static boolean doit(File path) {
Step step = new Step()
{
@Override public boolean step(File path) {
System.out.println(path);
return true;
}
};
return new PathRunner(path).run(step);
}
}