编写程序,实现当用户输入姓名和密码时,将每一个姓名和密码加在文件 中,如果用户输入done,就结束程序。
Java从入门到精通(第四版)P289,这里答案怪怪的,而且网上很多都有一点点bug。
修改了一下,并自己增了一些东西。
import java.io.*;
public class UseCase3 {
static final int lineLength = 81;
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("word.txt");
while (true) {
byte[] phone = new byte[lineLength];// 放在while里,每回数组重新生成,避免上次遗留的数据干扰。
byte[] name = new byte[lineLength];
System.out.print("请输入名字:");
readLine(name);
// System.out.println(new String(name).trim());
if ("done".equalsIgnoreCase(new String(name).trim())) {//name数组中有81个字节,判断时要去除空字符
// System.out.println();
System.out.println("录入完毕\n");
break;
}
System.out.print("请输入密码:");
readLine(phone);
fos.write("姓名:".getBytes());
for (int j = 0; name[j] != 0; j++) {
fos.write(name[j]);
}
fos.write(" 密码:".getBytes());
for (int i = 0; phone[i] != 0; i++) {
fos.write(phone[i]);
}
fos.write('\n');
System.out.println("--------信息已经写入文件--------");
}
fos.close();
} catch (Exception e) {
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;
}
}
运行结果如下: