一道有关Java中I/O流的题,实现当用户输入姓名和密码时,将每一个姓名和密码加在文件中,如果用户输入done,就结束程序。

网上(https://www.cnblogs.com/bby2014210552/p/5942698.html)的代码有些许错误,程序在输入done后无法停止,我自己想了一下改了改,运行是没问题的,如果有人有其他的建议还请告诉我。

源代码如下:

import java.io.*;

public class Example {
static final int lineLength = 81;

public static void main(String[] args) {
	FileOutputStream fos = null;
	byte[] phone = new byte[lineLength];
	byte[] name = new byte[lineLength];
	try {
		fos = new FileOutputStream("word.txt");
		while (true) {
			System.err.println("请输入一个名字:");
			readLine(name);
			if ("done".equalsIgnoreCase(new String(name).trim())) {//name数组中有81个字节,除去输入的,剩下的全是空格,判断时要去除空格
				System.out.println("录入完毕");
				break;
			}
			System.err.println("请输入电话号:");
			readLine(phone);
			for (int j = 0; name[j] != 0; j++) {
				fos.write(name[j]);
			}
			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[] data) throws IOException {
	int b = 0, i = 0;
	while ((i < (lineLength - 1)) && (b = System.in.read()) != '\n') {//不输入回车则循环继续
		data[i++] = (byte) b;
	}
	data[i] = (byte) 0;
}

}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值