I/O processing exercise-Save the user account password and account
I/O processing exercise-save user account and password
The user enters the name and password, saves each name and password to the file, and ends when the user enters the done.
1 import java. io. *; 2 3 public class Example {4 public static void main (String [] args) {5 byte [] name = new byte [20]; 6 byte [] password = new byte [20]; 7 File file = new File ("word.txt"); 8 try {9 FileOutputStream out = new FileOutputStream (file ); 10 while (true) {11 System. out. println ("Enter the User name:"); 12 System. in. read (name); 13 if ("done ". equals (new String (name, 0, 4) {14 break; 15} 16 System. out. println ("enter the password :" ); 17 System. in. read (password); 18 for (int I = 0; name [I]! = 0; I ++) {19 out. write (name [I]); 20} 21 for (int I = 0; password [I]! = 0; I ++) {22 out. write (password [I]); 23} 24} 25 out. close (); 26} catch (IOException e) {27 // TODO Auto-generated catch block28 e. printStackTrace (); 29} 30 31 32} 33 34}
Note the following:
1. FileOutputStream must be placed outside the loop. Otherwise, the content of the file will be overwritten and nothing will be saved at the end.
2. The length must be specified when determining done. Otherwise, this judgment condition cannot be successful and has a null value.
3. name [I]! The determination of = 0 is because the byte array has already defined the length, and null values in other places will also be written, resulting in a messy file format.
4. close the file output stream must be placed outside the while loop. If it is closed in advance, it cannot write the subsequent data.
The running result is as follows: