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
but when go to file locetion and open the txt file thre is not any thing in there.i use windows and my problem is with endenging the file i think..please help me with how to write on a file in java.tnx
The output from a java.util.Formatter
is not written immediately. Call flush() and the waiting data will be written immediately.
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`
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.