2015-01-22 1 views
-3

Я не могу напечатать то, что хочу напечатать, в файле «transaction-list.txt». Однако он создал файл, но при запуске программы он ничего не печатает. Предполагается, что он работает без проблем, просто не знаю почему.
Вот мой код:Я не могу напечатать вещи в outfile

final String acc_name= "Edward"; 
    final int acc_num=123456; 
    final int acc_password=456789; 
    boolean quit = false; 
    int i; 

    PrintWriter outFile = new PrintWriter("transaction-list.txt"); 
    outFile.println("HELLO!"); 

    //to output timestamp 
    String timestamp = new java.text.SimpleDateFormat("MM/dd/yyyy h:mm:ss").format(new Date()); 
    //System.out.print(timestamp); 

    //ask user to key in the account number and password and stores it into acc_num and acc_password variables 
    String stringAcc_num = JOptionPane.showInputDialog("Please enter your account number: "); 
    int Acc_num = Integer.parseInt(stringAcc_num); 

    String stringAcc_password = JOptionPane.showInputDialog("Please enter your account password: "); 
    int Acc_password = Integer.parseInt(stringAcc_password); 


    while (Acc_num != acc_num || Acc_password != acc_password){ 


     for (i = 1; i <= 2; i++) { 

      String error = "YOUR ACCOUNT NAME AND YOUR ACCOUNT PASSWORD IS NOT A MATCH!!"; 
      JOptionPane.showMessageDialog(null, error, "ALERT!", JOptionPane.ERROR_MESSAGE); 

      stringAcc_num = JOptionPane.showInputDialog("Please enter your account number: "); 
      Acc_num = Integer.parseInt(stringAcc_num); 

      stringAcc_password = JOptionPane.showInputDialog("Please enter your account password: "); 
      Acc_password = Integer.parseInt(stringAcc_password); 

      if (Acc_num == acc_num && Acc_password == acc_password) 
      break; 

     }//end for 


     if (i > 2){ 
      JOptionPane.showMessageDialog(null, "NO MORE TIRES!", "ALERT!", JOptionPane.ERROR_MESSAGE); 
      System.exit(0); 
     }//end if 


    }//end while 



    if (Acc_num == acc_num && Acc_password == acc_password){ 

     //to read the data from port-account.txt file 
     Scanner readFile = new Scanner (new FileReader("port-account.txt")); 

     //to create a txt file name "transaction-list.txt" 
     //PrintWriter outFile = new PrintWriter("transaction-list.txt"); 

     int current_balance = readFile.nextInt(); 

     do{ 

      //to pop out a message box 
      String stringOption = "1. Transfer an account" + "\n2. List recent transactions" + "\n3. Display account details and current balance" + "\n4. Quit" + "\nPlease enter a number base on the following options above."; 

      //to convert String into Int and stores it into "option" 
      int option = Integer.parseInt(JOptionPane.showInputDialog(null, stringOption, "Menu options", JOptionPane.INFORMATION_MESSAGE)); 


      switch(option){ 
      case 1: 
       String Case1 = JOptionPane.showInputDialog("Please enter an amount to transfer: "); 
       int amount_transfered = Integer.parseInt(Case1); 

       int newCurrent_balance = current_balance - amount_transfered; //data from port-account.txt - user input amount 

       JOptionPane.showMessageDialog(null, timestamp + "\nAmount transfered: $"+amount_transfered + "\nCurrent Balance: $"+newCurrent_balance, "Amount transfer complete!", JOptionPane.INFORMATION_MESSAGE); 

       //print it to transaction-list.txt file 
       outFile.println("Current Balance: $" + newCurrent_balance); 
      break; 

      case 2: 
       System.out.print("testing123! testing123!"); 
      break; 

      case 3: 
       JOptionPane.showMessageDialog(null, "\nAccount Name: "+acc_name + "\nAccount Number: "+acc_num + "\nCurrent Balance: $"+current_balance, "Account Details", JOptionPane.INFORMATION_MESSAGE); 
      break; 

      case 4: 
       System.exit(0); 
      break; 


      default: 
       JOptionPane.showMessageDialog(null, "The number you have input is invalid. Please try again.", "ERROR", JOptionPane.INFORMATION_MESSAGE); 
      }//end switch 

     }/*end do*/ while (!quit); //repeat do loop while "!quit"(not quit). 

     outFile.close(); 
     readFile.close(); 

    }//end if 

} 
} 
+0

Это довольно длинный код. Где именно вы делаете печать? Вы очищаете выходной поток? –

+0

Я не могу напечатать то, что хочу напечатать, в файле «transaction-list.txt». И я не знаю, почему, полагаю, это сработало. – EDP

+0

Какая строка в вашем коде должна печататься в файл? –

ответ

1

Вызов flush() на вашем outFile.

Хотя Javadoc для Writer говорит нам, что close() называет flush() первых, код в BufferedWriter#close() (который, лежащий в основе Writer из PrintWriter) фактически не очищать буфер (в отличие от BufferedWriter#flush()).

Таким образом, по существу, вы пишете только в буфер, который не обязательно вызывает запись в фактический выходной поток ОС, который не очищается при закрытии записи.

Избавьтесь от System.exit() звонок.

Вы также должны заметить, что если вы выходите с помощью вызова System.exit() (как правило, плохой практики) на одной из ветвей вашего коммутатора, то даже close() не вызывается.

NB

Вы могли бы легко решить это самостоятельно, если вы создали Minimal, Complete and Verifiable Example первый (который по сути будет тестовый модуль для вашего файла кода пишущего). Вы также не будете забиты из-за длинного отрывка кода, который в значительной степени не имеет отношения к проблеме, с которой вы столкнулись.

+0

Простите меня, я все еще новичок в Java, я еще не узнал о BufferedWriter, о котором вы только что упоминали. – EDP

+2

И close() вообще не будет вызываться при ярлыке для выхода через System.exit() ... – Fildor

+0

@ Fildor спасибо, добавил пару слов об этом. –

 Смежные вопросы

  • Нет связанных вопросов^_^