java中文本输入与输出

在保存数据是可以选择二进制格式或文本格式。文本格式更受人们的欢迎。
文本格式
OutputStringWriter类将使用指定的字符编码方式,把Unicode字符流转换为字节流
InputStringReader类将包含字节的输入流转换成可以产生Unicode码元的读入器

例如,下面的代码就展示了如何让一个输入读入器可以从控制台读入键盘敲击信息,并将其转换成Unicode

InputStringReader in=new InputStringReader(System.in);

这个是默认的,也可以选择不同的编码器,例如

InputStringReader in=new InputStringReader(new FileInputString("kremlin,dat"),"ISO08859_5");

如何写出文本输出
可以使用PrintWriter,这个类拥有以文本格式打印字符串和数字的方法,他甚至还有一个将PringWriter链接到FileWriter的便捷方法。下面的语句:

PrintWriter out=new PrintWriter("employee.txt");

等同于

PrintWriter out=new PrintWriter(new FileWriter("employee.txt"));

为了输出到打印写出器,需要使用与使用print、println、printf方法。可以用来打印数字,字符、boolean值、字符串和对象。

String name="Harry Hacker";
double salary=75000;
out.print(name);
out.print('  ');
out.println(salary);

它将把下面的字符:
Harry Hacker 75000.0
输出到写出器out,之后这些字符会被转换成字节并最终写入employee.txt。


如何读入文本输入
众所周知

  • 以二进制格式写出数据,需要使用DataOutputString.
  • 以文本格式写出数据,需要使用PrintWriter
    处理文本输入的方式BufferedReader
BufferedReader in=new BufferedReader(
   new InputStringReader(new FileInputStream(employee.txt),"UTF-8"));

readLine方法在没有输入时返回null,下面是一个典型的输入循环

String line;
while((line=in.readLine())!=null){
    doing sth with line;
}

然而BufferedReader没有任何用于读入数据的方法,建议使用Scanner来读入文本输入。


以文本格式存储对象
示例为将一个Employee记录数组存储成一个文本文件
使用PrintWriter类

public void writeData(PrintWriter out) throws IOException
{
   GregorianCalendar gregoriancalendar=new GregorianCalendar();
   calendar.setTime(hireDay);
   out.println(name+"|"+salary+"|"+calendar.get(Calendar.YEAR)+"|"+(calendar.get(Calendar.MONTH)+1)+"|"+calendar.get(Calendar.DAY_OF_MONTH));
}

为了读入记录,我们每次读入一行,然后分离所有字段。我们使用一个扫描器来读入每一行,然后用String.split方法将这一行断开成一组

public void readData(Scanner in)
{
    String line=in.nextLine();
    String[] tokens=line.split("//|");
    name=tokens[0];
    salary=Double.parseDouble(tokens[1]);
    int y=Integer.parseInt(tokens[2]);
    int m=Integer.parseInt(tokens[3]);
    int d=Integer.parseInt(tokens[4]);
     GregorianCalendar gregoriancalendar=new GregorianCalendar(y,m-1,d);
     hireDay=calendar.getTime();
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值