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

View File

@ -74,6 +74,12 @@ public class Files {
f.delete(); 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);
} }
} }