在程序中一个字符等于两个字节。
1、字符输出流:Writer
抽象类,需要通过FileWriter子类进行实例化
public FileWriter(File file) throws IOExcrption
【Writer类的常用方法】
* public abstract void close(0 throws IOException 关闭输出流
* public void write(String str) throws IOExcrption 将字符串输出
* public void write(char[] cbuf) throws IOException 将字符数组输出
* public abstaract void flush(0 throws IOEXception 强制清空缓存
实例:向文件中写入数据
public class WriterDemo {
public static void main(String[] args) {
File f = new File("D:"+File.separator+"test.txt");
try {
FileWriter writer = new FileWriter(f);
String str = "FileWriter";
//与OutputStream的区别就是不用将字符串变成数据,可以直接输出字符串
writer.write(str);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
向文件中追加内容,和OutputStream一样的方法:
public class WriterDemo {
public static void main(String[] args) {
File f = new File("D:"+File.separator+"test.txt");
try {
FileWriter writer = new FileWriter(f,true);
String str = "\r\nFileWriter";
//与OutputStream的区别就是不用将字符串变成数据,可以直接输出字符串
writer.write(str);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、字符输入流:reader
抽象类,通过FileReader类进行实例化
【Reader类常用方法】
* public abstract void close() throws IOException 关闭输出流
* public int read() throws IOExcrption 读取单个字符
public int read (char [] cbuf) throws IOExcrption 将内容读取字符数组中,返回读入的长度
public class ReaderDemo {
public static void main(String[] args) {
File file = new File("d:"+File.separator+"test.txt");
try {
FileReader reader = new FileReader(file);
char c[] = new char[1024];
int len = reader.read(c);
reader.close();
System.out.println("读取内容:"+new String(c,0,len));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
可以通过循环方式进行读写:
public class ReaderDemo {
public static void main(String[] args) {
File file = new File("d:"+File.separator+"test.txt");
try {
FileReader reader = new FileReader(file);
char c[] = new char[1024];
int temp = 0;
int len =0;
while ((temp = reader.read())!=-1) {
c[len] = (char)temp;
len++;
}
reader.close();
System.out.println("读取内容:"+new String(c,0,len));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}