在保存数据是可以选择二进制格式或文本格式。文本格式更受人们的欢迎。
文本格式
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();
}