Writer類與Reader類是以字符流傳輸數據,一個字符是兩個字節
字符流除了是以字符方式(兩個字節)傳輸數據外,另外一點與字節流不同的是字符流使用緩衝區,通過緩衝區再對文件進行操作。字節流字節對文件進行操作。使用字符流類時關閉字符流會強制將字符流緩衝區的類容輸出,如果不想關閉也將字符流進行輸出,使用Writer類的flush()方法。
Reader讀取數據:
try {
Reader reader = new FileReader(
"D:\\cmz\\java\\JavaOOP6.0\\pet.template");
char ch[] = new char[45];
StringBuffer buffer = new StringBuffer();
try {
int length = reader.read(ch);
while (length != -1) {
buffer.append(ch);
length = reader.read();
}
String str = " 您好!我的名字是{name},我是一隻{type}.我的主人是{master}";
System.out.println("替換前:" + str);
str = str.replace("{name}", "歐歐");
str = str.replace("{type}", "狗狗");
str = str.replace("{master}", "程沐喆");
System.out.println("替換後:" + str);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
使用writer操作數據:
String str = "您好!我的名字是歐歐,我是一隻狗狗.我的主人是李偉";
try {
FileWriter file = new FileWriter("D:\\cmz\\java\\JavaOOP6.0\\pet.template");
file.write(str);
if (null!=file) {
file.close();
System.out.println("寫入成功");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}