簡體   English   中英

在JAVA上打開文件

[英]opening files on JAVA

import java.util.Formatter;
import java.util.Scanner;

public class JavaApplication3 {

   public static void main( String[] args ) throws Exception
   {
      Formatter output = new Formatter( "clients.txt" ); // open the file
      Scanner input = new Scanner( System.in ); // reads user input

      int accountNumber; // stores account number
      String firstName; // stores first name
      String lastName; // stores last name
      double balance; // stores account balance

      System.out.printf( "%s\n%s\n%s\n%s\n\n",
         "To terminate input, type the end-of-file indicator ",
         "when you are prompted to enter input.",
         "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
         "On Windows type <ctrl> z then press Enter" );

      System.out.printf( "%s\n%s", 
         "Enter account number (> 0), first name, last name and balance.",
         "? " );

      while ( input.hasNext() ) // loop until end-of-file indicator
      {
         // retrieve data to be output
         accountNumber = input.nextInt(); // read account number
         firstName = input.next(); // read first name
         lastName = input.next(); // read last name
         balance = input.nextDouble(); // read balance

         if ( accountNumber > 0 )
         {
            // write new record
            output.format( "%d %s %s %.2f\n", accountNumber, 
               firstName, lastName, balance );
         } // end if
         else
         {
            System.out.println(
               "Account number must be greater than 0." );
         } // end else

         System.out.printf( "%s %s\n%s", "Enter account number (>0),",
            "first name, last name and balance.", "? " );
      } // end while

      output.close(); // close file
   } // end main
} // end class CreateTextFile

但是當轉到文件位置並打開txt文件時,那里沒有任何東西。我使用Windows,我的問題是使用我認為的文件。.請幫助我如何在java.tnx中寫文件

java.util.Formatter的輸出不會立即寫入。 調用flush() ,等待的數據將立即寫入。

   if ( accountNumber > 0 )
     {
        // write new record
        output.format( "%d %s %s %.2f\n", accountNumber, 
           firstName, lastName, balance );
           output.flush();//missing this line
     }
java.util.Formatter will not write until flush() method is called.
    if ( accountNumber > 0 ){
    // write new record
    output.format( "%d %s %s %.2f\n",accountNumber,firstName,lastName,balance );
    output.flush(); // this is missed.
    } // end if`enter code here`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM