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
但是当去文件locetion并打开txt文件时,没有任何东西在那里。我使用windows,我的问题是重复文件我认为..请帮助我如何在java中的文件上写。 TNX
答案 0 :(得分:0)
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
}
答案 1 :(得分:-1)
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`