2015-02-11 57 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(); 
}