编写程序,实现当用户输入姓名和密码时,将每一个姓名和密码加在文件 中,如果用户输入done,就结束程序。

编写程序,实现当用户输入姓名和密码时,将每一个姓名和密码加在文件 中,如果用户输入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;
    }
}

运行结果如下:
IDEA
输出文件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值