fix bugs in File.getParent and listFiles

getParent should return the same value regardless of whether it ends
in a file separator, and listFiles should return null for
non-directories.
This commit is contained in:
Joel Dice 2012-07-31 09:27:18 -06:00
parent c17710d2b0
commit 836fc21106
2 changed files with 37 additions and 19 deletions

View File

@ -148,9 +148,13 @@ public class File implements Serializable {
}
public String getParent() {
int index = path.lastIndexOf(FileSeparator);
String p = path;
while (p.endsWith(FileSeparator)) {
p = p.substring(0, p.length() - 1);
}
int index = p.lastIndexOf(FileSeparator);
if (index >= 0) {
return path.substring(0, index);
return p.substring(0, index);
} else {
return null;
}
@ -239,11 +243,15 @@ public class File implements Serializable {
public File[] listFiles(FilenameFilter filter) {
String[] list = list(filter);
if (list != null) {
File[] result = new File[list.length];
for (int i = 0; i < list.length; ++i) {
result[i] = new File(this, list[i]);
}
return result;
} else {
return null;
}
}
public String[] list() {
@ -254,6 +262,7 @@ public class File implements Serializable {
long handle = 0;
try {
handle = openDir(path);
if (handle != 0) {
Pair list = null;
int count = 0;
for (String s = readDir(handle); s != null; s = readDir(handle)) {
@ -270,6 +279,9 @@ public class File implements Serializable {
}
return result;
} else {
return null;
}
} finally {
if (handle != 0) {
closeDir(handle);

View File

@ -74,6 +74,12 @@ public class Files {
f.delete();
}
}
expect(new File("foo/bar").getParent().equals("foo"));
expect(new File("foo/bar/").getParent().equals("foo"));
expect(new File("foo/bar//").getParent().equals("foo"));
expect(new File("foo/nonexistent-directory").listFiles() == null);
}
}