网上(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;
}
}