在程序中一个字符等于两个字节,Java提供了Reader和Writer两个专门操作字符的类。
1.字符流输出Writer类
同样,该类本身为一个抽象类,通过其子类实现具体的操作
FileWriter的构造方法如下:
public FileWriter(File file) throws IOException
2.字符流输出实例程序如下
package stringText;
import java.io.*;
public class WriterAndReader {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
/*
* 例1 Writer直接输出字符串
*/
// 第一步,使用File类找到一个文件
File f = new File("d:\\test\\1.txt");
// 第二步,通过子类实例化父类对象
Writer out = null;
out = new FileWriter(f);
// 第三步,定义字符串并输出
String s = " Hello World With Writer";
out.write(s);
// 第四步,关闭输出流
out.close();
/*
* 例2 追加字符串内容
*/
// 第一步,使用File类找到一个文件
File f1 = new File("d:\\test\\1.txt");
// 第二步,通过子类实例化父类对象
Writer out1 = null;
out1 = new FileWriter(f1, true);
// 第三步,定义字符串并输出
String s1 = " Add Hello World With Writer";
out1.write(s1);
// 第四步,关闭输出流
out1.close();
}
}
3.字符输入流Reader
子类FileReader的构造方法为:
public FileReader(File file) throws FileNotFoundException
4.字符输入流事例如下
package stringText;
import java.io.*;
public class WriterAndReader {
public static void main(String[] args) throws Exception {
/*
* 例1 输入流中输入字符串
*/
//第一步,使用File类找到一个文件
File f2=new File("d:\\test\\1.txt");
//第二步,通过子类实例化父类的对象
Reader reader=new FileReader(f2);//准备一个输入流对象
//第三步,进行读写操作
char c[]=new char[1024];
int len=reader.read(c); //获取文件的长度
//第四步,关闭输入流
reader.close();
System.out.println("内容为:"+new String(c,0,len));
/*
* 例2 输入流中输入字符串(利用循环方式)
*/
//第一步,使用File类找到一个文件
File f3=new File("d:\\test\\1.txt");
//第二步,通过子类实例化父类的对象
Reader reader1=new FileReader(f2);//准备一个输入流对象
//第三步,进行读写操作
char c1[]=new char[1024];
int len1=0; //获取文件的长度
int temp=0; //接收读取的每一个内容
//第四步,关闭输入流
while((temp=reader1.read())!=-1){
c1[len1]=(char)temp;
len1++;
}
reader.close();
System.out.println("内容为:"+new String(c1,0,len));
}
}