I/O processing exercise-Save the user account password and account

Source: Internet
Author: User

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:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.