java - Using renameTo on File changes the content -


file dir = new file(getfilesdir(), "dir1"); dir.renameto(new file(getfilesdir(), "dir2"); log.d("number of files:", dir.listfiles().length); 

suppose /dir1/ contains 5 files. code print 0.however, if change code to`

file dir = new file(getfilesdir(), "dir1"); dir.renameto(new file(getfilesdir(), "dir2"); dir = new file(getfilesdir(), "dir2"); log.d("number of files:", dir.listfiles().length); 

it print correct value: 5. there reason that? looks dir not link same directory after use renameto.

the reason in first code dir still pointing directory dir1 , not dir2.

however, in following code:

file dir = new file(getfilesdir(), "dir1"); dir.renameto(new file(getfilesdir(), "dir2"); dir = new file(getfilesdir(), "dir2"); log.d("number of files:", dir.listfiles().length); 

dir pointing dir2, , got correct value.

i'll suggest avoid using java's file.renameto() since problematic, on windows. api documentation says:

many aspects of behavior of method inherently platform-dependent: rename operation might not able move file 1 filesystem another, might not atomic, , might not succeed if file destination abstract pathname exists. return value should checked make sure rename operation successful.

you can use apache.commons.io library, includes fileutils.movefile() or files.move() method in jdk 7.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -