![](/img/trans.png)
[英]How to set the file directory so that it will work without the full file path?
[英]How to access directory with full file path?
因此,我正在編寫一個程序,該程序需要遍歷目錄中的所有文件,這就是我目前擁有的程序。
import java.io.File;
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws Exception {
VotingData v = new VotingData();
Scanner in = new Scanner(System.in);
System.out.print("Please input a directory.");
String input = in.next();
File dir = new File(input);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
v.merge(RecordReader.readRecord(child.toString()));
}
}
else {
// do nothing right now.
}
String[] sub1 = {"Montgomery","Miami"};
TextualRepresentation.toString(v.getAllResults());
TextualRepresentation.toString(v.getCountyResults("Montgomery"));
TextualRepresentation.toString(v.getCountyResults("Miami"));
TextualRepresentation.toString(v.getCountyResults("Butler"));
TextualRepresentation.toString(v.getSubsetResults(sub1));
}
}
該項目的文件路徑為C:\\ Users \\ Jarrett Willoughby \\ Documents \\ School \\ CSE201 \\ Project Stuff。
我正在嘗試的輸入是“ C:\\ Users \\ Jarrett Willoughby \\ Documents \\ School \\ CSE201 \\ Project Stuff \\ TestFiles”,但它似乎不起作用。 但是,當輸入只是“ TestFiles”時,它就會執行。 我希望能夠訪問不同文件夾中的目錄,但是由於某種原因,長方法無法正常工作。
編輯:我不知道錯誤是什么。 我所知道的是,當我將“ TestFiles”放入掃描儀時,它可以正常工作,當我嘗試使用完整的文件路徑時,它不會崩潰,但不會產生我想要的結果。
Scanner#next()
讀取由空格分隔(默認情況下)的字符串標記。
您的輸入:
C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff\TestFiles
包含空格,因此next()
僅讀取“ C:\\ Users \\ Jarrett”。
您可以改用Scanner#nextLine()
。
將來,要自己進行調試,請逐步進入調試器以查看變量具有哪些值,或者添加打印輸出進行驗證,例如,這將使您快速找到解決方案:
System.out.println("input was " + input);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.