I/O處理小練習--儲存使用者帳號密碼,帳號

來源:互聯網
上載者:User

I/O處理小練習--儲存使用者帳號密碼,帳號
I/O處理小練習--儲存使用者帳號密碼

使用者輸入姓名和密碼,將每一個姓名和密碼儲存到檔案中,輸入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("請輸入使用者名稱:");12             System.in.read(name);13             if("done".equals(new String(name, 0, 4))){14                 break;15             }16             System.out.println("請輸入密碼:");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 }

需要注意的幾個的地方:

1.FileOutputStream一定要放在迴圈之外,否則這個檔案的內容會一直覆蓋,最後什麼也存不到

2.判定done的時候,一定要規定長度,要不然這一判斷條件不可能成功,有空值

3.name[i]!=0的判定是因為位元組數組是已經定義好了長度的,其他地方的空值也會被寫入,導致檔案內的格式很亂

4.檔案輸出資料流的關閉一定要放在while迴圈之外,提前關閉了就無法寫入後面的資料了

運行結果如下:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.