Java_I/O輸入輸出_實現當用戶輸入姓名和密碼時,將每一個姓名和密碼加在文件中,如果用戶輸入done,就結束程序。


import java.io.*;

public class Example {
static final int lineLength = 81;

public static void main(String[] args) {
FileOutputStream fos;

byte[] phone = new byte[lineLength];
byte[] name = new byte[lineLength];
try {
fos = new FileOutputStream("word.txt");
while (true) {
System.err.println("請輸入一個名字:");
if ("done".equalsIgnoreCase(new String(name, 0, 0, 4))) {
System.out.println("錄入完畢");
break;
}
System.err.println("請輸入電話號:");
readLine(phone);
for (int i = 0; phone[i] != 0; i++) {
fos.write(phone[i]);
}
fos.write(',');
for (int j = 0; name[j] != 0; j++) {
fos.write(name[j]);
}
fos.write('\n');
System.out.println("信息已經寫入文件");
}
fos.close();
} catch (Exception e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
}

private static void readLine(byte[] name) throws IOException {
int b = 0, i = 0;
while ((i < (lineLength - 1)) && (b = System.in.read()) != '\n') {
name[i++] = (byte) b;
}
name[i] = (byte) 0;
}

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM