2015-02-11 50 views
0

爲了這個任務的目的,我們被要求製作一個使用文件類的程序(我知道輸入流比較好),但是,我們必須要求用戶輸入.txt文件的名稱。用戶輸入他們想要讀取的文件名稱?

public class input { 

public static void main(String[] args) throws FileNotFoundException { 
    Scanner s = new Scanner(System.in); 
    String name; 
    int lineCount = 0; 
    int wordCount = 0; 


    System.out.println("Please type the file you want to read in: "); 
    name = s.next(); 

    File input = new File("C:\\Users\\Ceri\\workspace1\\inputoutput\\src\\inputoutput\\lab1task3.txt"); 
    Scanner in = new Scanner(input); 

我怎麼會得到

File input = new File(...); 

搜索的文件只是打字 'lab1task3' 不起作用。

編輯: - 錯誤

Exception in thread "main" java.io.FileNotFoundException: \lab1task3.txt (The system cannot find the file specified) 
at java.io.FileInputStream.open(Native Method) 
at java.io.FileInputStream.<init>(Unknown Source) 
at java.util.Scanner.<init>(Unknown Source) 
at inputoutput.input.main(input.java:19) 
+0

你想要得到的'File'給定文件夾裏面?或者你想搜索整個文件系統? – MinecraftShamrock 2015-02-11 17:26:01

+0

你會得到什麼錯誤?應該搜索該文件還是隻是打開它? – Cyphrags 2015-02-11 17:26:12

+0

@MinecraftShamrock是在給定的文件夾或相關文件夾中。 – 2015-02-11 17:27:08

回答

0

要搜索特定文件夾中的文件,你可以只通過迭代指定文件夾中的文件:

File givenFolder = new File(...); 
String fileName = (...); 
File toSearch = findFile(givenFolder, fileName); 

凡功能的FindFile (文件夾,字符串文件名)將迭代givenFolder中的文件並嘗試查找該文件。它看起來是這樣的:

public File findFile(File givenFolder, String fileName) 
{ 
    List<File> files = getFiles(); 
    for(File f : files) 
    { 
    if(f.getName().equals(fileName)) 
    { 
     return f; 
    } 
    } 
    return null; 
} 

功能的GetFiles只是遍歷在給定文件夾中的所有文件,並調用它的自我發現的文件夾時:

public List<File> getFiles(File givenFolder) 
{ 
    List<File> files = new ArrayList<File>(); 
    for(File f : givenFolder.listFiles()) 
    { 
    if(f.isDirectory()) 
    { 
     files.addAll(getFiles(f)); 
    } 
    else 
    { 
     files.add(f); 
    } 
    } 
} 

我希望這可以幫助你: )如果你想知道更多關於這裏發生的事情,請隨時詢問:)

1

掃描儀無法以這種方式讀取文件,您需要先將它存儲爲文件! 如果你把它放在一個try-catch塊中,你可以確保如果找不到文件,程序不會中斷。我建議將其封裝在do-while/while循環中(取決於結構),最終條件是找到該文件。

我改變你的主要方法,這和它的正確編譯:

public static void main(String[] args) throws FileNotFoundException { 
    Scanner sc = new Scanner (System.in); 

    System.out.println("Please type the file you want to read in: "); 
    String fname = sc.nextLine(); 

    File file = new File (fname); 
    sc.close(); 
} 
相關問題