首页 > 代码库 > Java学习笔记之 IO包 字符流
Java学习笔记之 IO包 字符流
字符流:Writer/Reader(字符流)
通过子类FileWriter和FileReader实现父类实例化
package iotest;
import java.io.File;
import java.io.Writer;
import java.io.Reader;
import java.io.FileWriter;
import java.io.FileReader;
public class OutputStreamDemo2 {
public static void main(String args[]) throws Exception{
File f =new File("D:"+File.separator+"javasrc"+File.separator+"write_file.txt");
//写数据入文件
Writer w=new FileWriter(f);
String s="Jerry Wang!!";
w.write(s);
w.close();
//追加数据到文件
Writer w1=new FileWriter(f,true);
w1.write("\r\n");
w1.write(s);
w1.close();
//通过字符流读取文件
Reader r=new FileReader(f);
char c[]=new char[1024];
int len=r.read(c);
r.close();
print("the first read method:");
print(c,len);
//未知文件长度 读取文件
Reader r2=new FileReader(f);
char c2[]=new char[1024];
int temp=0;
int i=0;
while((temp=r2.read())!=-1){
c2[i]=(char)temp;
i++;
}
r2.close();
print("the second read method:");
print(c2,len);
}
public static void print(char b[],int len){
System.out.println(new String(b,0,len));
}
public static void print(char b[]){
System.out.println(new String(b));
}
public static void print(String b){
System.out.println(b);
}
}
Java学习笔记之 IO包 字符流