From 836fc211068b76be1f8ff3068ccc1d7f1a528177 Mon Sep 17 00:00:00 2001 From: Joel Dice Date: Tue, 31 Jul 2012 09:27:18 -0600 Subject: [PATCH] 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. --- classpath/java/io/File.java | 50 +++++++++++++++++++++++-------------- test/Files.java | 6 +++++ 2 files changed, 37 insertions(+), 19 deletions(-) diff --git a/classpath/java/io/File.java b/classpath/java/io/File.java index 86e093495b..d8bfd474b4 100644 --- a/classpath/java/io/File.java +++ b/classpath/java/io/File.java @@ -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); - File[] result = new File[list.length]; - for (int i = 0; i < list.length; ++i) { - result[i] = new File(this, list[i]); + 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; } - return result; } public String[] list() { @@ -254,22 +262,26 @@ public class File implements Serializable { long handle = 0; try { handle = openDir(path); - Pair list = null; - int count = 0; - for (String s = readDir(handle); s != null; s = readDir(handle)) { - if (filter == null || filter.accept(this, s)) { - list = new Pair(s, list); - ++ count; + if (handle != 0) { + Pair list = null; + int count = 0; + for (String s = readDir(handle); s != null; s = readDir(handle)) { + if (filter == null || filter.accept(this, s)) { + list = new Pair(s, list); + ++ count; + } } - } - String[] result = new String[count]; - for (int i = count - 1; i >= 0; --i) { - result[i] = list.value; - list = list.next; - } + String[] result = new String[count]; + for (int i = count - 1; i >= 0; --i) { + result[i] = list.value; + list = list.next; + } - return result; + return result; + } else { + return null; + } } finally { if (handle != 0) { closeDir(handle); diff --git a/test/Files.java b/test/Files.java index 7a0170b678..e613bd4fc1 100644 --- a/test/Files.java +++ b/test/Files.java @@ -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); } }