2009年2月3日 星期二

Question 5

The doesFileExist method takes an array of directory names representing a path from the root filesystem and a filename.The

method returns true if the file exists,false if does not.

Place the code fragments in position to complete this method.

//insert here A
for(String dir:directories){
//insert here B
}

//insert here C

//insert here D

Code Fragments

1.path = path.getSubdirectory(dir);
2.return !file.inNew();
3.return (file!=null);
4.String path="";
5.path = path.getFile(filename);
6.File path = new File("");
7.return file.exist();
8.return path.isFile();
9.File file = new File(path,filename);
10.path = new File(path,dir);
11.File path = new File(File.separator);
12.path = path+FileSeparator+dir;

當然了,要想做出這道題目,首先要知道這個程式段想要做什麼,要完成什麼任務.

這是從doesFileExist方法中截取的一段代碼,doesFileExist方法完成的主要功能是:這個方法會獲得一個字串陣列和一個檔案名.這個字元

串陣列存放的是從根目錄開始的一個路徑.doesFileExist方法中,如果檔存在,返回true,如果不存在,返回false;

既然知道了要做什麼事情,我們就很清楚的知道我們要去做什麼事情了:

首先,我們要先把字串陣列中的元素依次取出來,把它們連接到一起,形成一個完整的絕對路徑.然後,創建用這個路徑和已經得到的檔案名做

參加,生成一個File物件,利用File物件的exist()方法,來判斷這個檔是否存在.

那麼,我們的答案是什麼呢:
A:4
B:12
C:9
D:7

我也試著寫了一下測試類

import java.io.File;

public class Tester {
public static void main(String[] args) {
String[] directories = new String[] { "D:", "homework", "d0427" };
String filename = "table.xml";
System.out.println(doesFileExist(directories, filename));
}
public static boolean doesFileExist(String[] directories, String filename) {
String path = "";
for (String dir : directories) {
path = path + File.separator + dir;
}
File file = new File(path, filename);
return file.exists();
}
}

在我的電腦裏,D:\homework\d0427確實存在著一個檔table.xml,所以,返回值為true
本貼來自ZDNetChina中文社區 http://bbs.zdnet.com.cn ,本貼地址:http://bbs.zdnet.com.cn/viewthread.php?tid=384016

沒有留言:

張貼留言