带循环检查和try catch块的文件输出

时间:2014-04-02 22:08:51

标签: while-loop try-catch fileoutputstream

在文件输出和使用try / catch时遇到一些麻烦。我试图基本上说,如果用户输入现有文件名,请保持循环,直到输入有效的文件名。但是,我似乎无法让它工作。关于我哪里出错的任何提示?尝试在try块周围移动初始提示但是不会使范围仅在try块中可用?基本上,我应该在外部提示,以便它可用于所有try / catch块?不过不确定。

 import java.util.Scanner;
 import java.io.File;  
 import java.io.IOException;
 import java.io.PrintWriter;

 public class TestAccountWithException 
 {

    public static void main(String[] args) throws IOException 
    {

    // variable declaration
    String fileName;
    String firstName;
    String lastName;
    double balance;
    int id = 1122;
    final double RATE = 4.50;

    Scanner input = new Scanner(System.in);
    System.out.print("Please enter file name: ");
    fileName = input.next();
    File fw = new File(fileName);

    try 
        {

            // check if file already exists
            while(fw.exists()) 
            {
                System.out.print("File already exists. Enter valid file name: ");
                fileName = input.next();
                fw = new File(fileName);
            }   


            System.out.print("Enter your first name: ");
            firstName = input.next();

            System.out.print("Enter your last name: ");
            lastName = input.next();

            System.out.print("Input beginnning balance: ");
            balance = input.nextDouble();   

            // pass object to printwriter and use pw to write to the file
            PrintWriter pw = new PrintWriter(fw);

            // print to created file
            pw.println(firstName);
            pw.println(lastName);
            pw.println(balance);
            pw.println(id);
            pw.println(RATE);
            pw.close();
            //      System.out.print("Run program? (1) Yes (2) No: ");
            //      cont = input.nextInt();


        } catch (IOException e) {

            e.printStackTrace();

        }

    } // end main
  } // end class

1 个答案:

答案 0 :(得分:0)

您可能更喜欢使用java.nio.file。使用这个java 7包,您可以使用

while(true) {
  String fileName = input.next();
  Path path = Paths.get(fileName);
  if (Files.exists(path)) {
     try {
     // file exists 
     // your operations
     } catch {

     }
     break;
   } else {
      // not found
      fileName = input.next();
   }
 }