日期:2014-05-20  浏览次数:20840 次

关于File类中的一个问题
package myday20;

import java.io.File;

public class fileName{

public static void main(String[] args) throws Exception {

File f = new File("src/myday20");
 test1(f);
 System.out.println("------------------");

listMyFiles(f);
}

public static void test1(File file) {
if (file.isDirectory()) {
String[] s = file.list();
for (String string : s) {
System.out.println(string);
}
System.out.println("--------------------------");
int length = s.length;
File[] files = new File[length];
System.out.println(files.length);
System.out.println(files[0]);
files[0] = new File(s[0]);
System.out.println(files[0]);// 这里输出的为什么是文件名字而不是地址?

// for (int i = 0; i < length - 1; i++) {
// files[i] = new File(s[i]);
// System.out.println(files[i]);
// }
// for (int i = 0; i < length - 1; i++) {
// test1(files[i]);
// }
} else {
System.out.println(file.getName() + " " + "is not directory");
}
}

public static void listMyFiles(File file) {
if (file.isDirectory()) {
File[] fs = file.listFiles();
for (File file2 : fs) {
System.out.println(file2);
}
for (File file2 : fs) {
listMyFiles(file2);
}
}
}
}


------解决方案--------------------

 //List the elements of the directory denoted by the given abstract
 //pathname.  Return an array of strings naming the elements of the
 //directory if successful; otherwise, return <code>null</code>.
 
 public abstract String[] list(File f);

先看一下File的list方法,实际调用了FileSystem的list方法,上面是FileSystem.list(File f)的描述,意思是成功则返回给定路径下的所有元素名字的String数组,所以这里只有文件名

public File(String pathname) {
if (pathname == null) {
    throw new NullPointerException();
}
this.path = fs.normalize(pathname);
this.prefixLength = fs.prefixLength(this.path);
    }

 /**
  * Convert the given pathname string to normal form.  If the string is
  * already in normal form then it is simply returned.
  */
  public abstract String normalize(String path);

再看File 构造函数,可以看出传进去的名字被FileSystem.normalize方法处理,看这个方法描述,将所给的路径转换成正常形式,如果是正常形式则简单返回,所以这里将文件名保存了

 public String toString() {
return getPath();
    }

File的toString() ,可以看出打印了path