关于IO输出输出流的一道题

熊黄酒_H 2016-12-25 04:59:17
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;
}

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

请教
1、这个是要怎么输入姓名和密码执行程序操作
2、while ((i < (lineLength - 1)) && (b = System.in.read()) != '\n') {
name[i++] = (byte) b;
}
name[i] = (byte) 0; 这里又是什么意思??
还望大神们赐教!!
...全文
314 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
lipengzhu 2016-12-30
  • 打赏
  • 举报
回复
由于FileOutputStream是字节流,只能输出以字节为单位的数据 , readLine(byte[] name) 方法将键盘输入凑成一个字节数组, 当遇到回车时将字节数组的最后一个字节取0,分别在 for (int i = 0; phone[i] != 0; i++)和for (int j = 0; name[j] != 0; j++) 循环中用到,相等于判断"字符串"的结束符。 这种直接使用节点流来处理的方法现在比较少见了,通常可以使用缓冲 流或其他过滤流代替,因为缓冲流有readLine()方法,可以实现类似功能。
熊黄酒_H 2016-12-26
  • 打赏
  • 举报
回复
Java_I/O输入输出_实现当用户输入姓名和密码时,将每一个姓名和密码加在文件中,如果用户输入done,就结束程序。 它要实现的就是这个功能 ,然后代码我直接copy过来,但是我看不懂他是怎么执行的,以及这样执行有什么实际意义
qq_36151437 2016-12-25
  • 打赏
  • 举报
回复
是不是少写readLine(name)了
qq_36151437 2016-12-25
  • 打赏
  • 举报
回复
说第二个问题吧,其所进行的操作即是把数组的最后一个值赋值为值为0的字节。

62,625

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧