java1.0中使用InputStream和OutputStream,面向字节的,8位
java1.1中使用Reader和Writer,基于字符,16位
static String read(String filename){
BufferedReader bf = new BufferedReader(new FileReader(filename))
StringBuilder sb = new StringBuilder();
while((s = bf.readLine()) != null){
sb.append(s+"\n");
}
in.close();
return sb.String();
}
static void writeToFile(String content, String outName){
// String
PrintWriter out = new PrintWriter(outName);
out.write(content.getbytes());
out.close();
}
DataInputStream和DataOutputStream
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data.txt")));
out.writeUTF("hello world");
out.writeDouble(5.3);
out.writeInt(1);
out.close();
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("data.txt")));
System.out.println(in.readUTF()+" " + in.readDouble()+"," + in.readInt());
写字符串时,out.writeUTF(str)是因为
UTF-8将ASCII编码成单一字节,而非ASCII字符编码成两到三个字节。
java中的writeUTF使用的是UTF8的变体
对象读写:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("a.txt"));
Date data = new Date();
out.writeObject(date);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("a.txt"));
Date d = (Date)in.readObject();