io - Java - Moving files within filesystem -
i working on school assignment , doing simple filemanager should move files suffix "jpg"
(for example) folder. problem should recursively through folders.
example: in folder "downloads":
--downloads ----me.jpg ----smth.doc ----folder1 ------you.jpg
and have move .jpg files folder "photos" , create "folder1" there , move file "you.jpg"
this have seems move files "downloads folder"
private void move(string suffix, string sourcepath, string destination) throws ioexception{ file dir = new file(sourcepath); file destdir = new file(destination); string src; string dst; (file f : dir.listfiles(new extensionfilter(suffix))){ string name = f.getname(); src = f.getabsolutepath(); dst = destination + "\\" + name; files.createdirectories(paths.get(destination)); files.move(paths.get(src), paths.get(dst)); logs.add("mv;" + src + ";" + dst); } (file f : dir.listfiles(new directoryfilter())){ move(suffix, f.getpath(), destination + "\\" + f.getname()); } }
logs arraylist save log files have been moved
this lot easier using java nio.2 api in combination java 8.
java 8 introduced method files.walk(path)
returns stream of paths under given path, recursively:
return
stream
lazily populatedpath
walking file tree rooted @ given starting file.
a proposed solution following:
private void move(string suffix, path source, path destination) throws ioexception { files.createdirectories(destination); files.walk(source) .filter(p -> p.tostring().endswith(suffix)) .foreach(p -> { path dest = destination.resolve(source.relativize(p)); try { files.createdirectories(dest.getparent()); files.move(p, dest); } catch (ioexception e) { throw new uncheckedioexception(e); } }); }
this code creates destination path. walks starting source path , filters paths ends given suffix. finally, each of them:
source.relativize(p)
returns relative path source path.for example, on unix, if path "/a/b" , given path "/a/b/c/d" resulting relative path "c/d".
as such, return part of path under source can copy target path.
destination.resolve(other)
returns path constructed appending path other path:in simplest case, [...], in case method joins given path path , returns resulting path ends given path.
- so now, have full target path. first need create parent directories
files.createdirectories(dir)
.dest.getparent()
returns parent path, say, drops filename path. final step moving source path target pathfiles.move(source, target)
.
if can't upgrade java 8 yet , keep java 7, can still use files.walkfiletree
instead of files.walk
(the rest of code need adjustment idea same).
Comments
Post a Comment