使用try / catch块从文本文件中读取

时间:2013-12-15 19:12:42

标签: java loops netbeans while-loop try-catch

所以即时尝试从文件中读取单词的数量并将它们添加到给出和int答案?并且帮助和/或建议会很好,我只能使用try / catch for for循环和if / else / if ....谢谢!

这是我到目前为止所得到的:

package filereadingexercise2;

import java.io.*;
import java.util.Scanner;

/**
 *
 * @author theGreggstar
 */
public class FileReadingExercise2 
{
  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) 
  {
    Scanner keys = new Scanner(System.in); 
    String nameOfFile;

    System.out.print("Please Enter The Name Of A File Or Directory, or Type Quit To Exit: ");
    nameOfFile = keys.nextLine();

    Scanner input = null;
    try
    {
      input = new Scanner(new File(nameOfFile));
    }
    catch(FileNotFoundException s)
    {
      System.out.println("File does Not Exist Please Try Again: ");
    }

    while(input.hasNext())
    {
      String contents = input.next();
      int length;

      System.out.print(contents);       
    }
  }
}

1 个答案:

答案 0 :(得分:2)

如果我理解正确,你想要这样的东西 -

public static void main(String[] args) {
  Scanner keys = new Scanner(System.in);
  for (;;) { // Loop forever.
    System.out.print("Please Enter The Name Of A File Or "
        + "Directory, or Type Quit To Exit: ");
    String nameOfFile = keys.nextLine().trim(); // get the User input.
    if (nameOfFile.equalsIgnoreCase("quit")) {  // check for exit condition.
      break;
    }
    File f = new File(nameOfFile);              // Construct a File.
    if (f.exists()) {                           // Does it exist?
      if (f.isFile() && f.canRead()) {          // is it a File and can I read it?
        Scanner input = null;
        try {
          input = new Scanner(f);               // The Scanner!
          while (input.hasNextLine()) {
            String contents = input.nextLine();
            System.out.println(contents);       // Print the lines.
          }
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } finally {
          if (input != null) {
            input.close();                      // Close the file scanner.
          }
        }
      } else if (f.isDirectory()) {             // No, it's a directory!
        try {
          System.out.println("File "
              + f.getCanonicalPath()
              + " is a directory");
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
}