您的位置:首页 > 其它

字符流的使用

2014-01-09 09:56 218 查看
package fileIO;
import java.io.*;

public class CharDemo {

/**
* 一般在操作文件流时,不管字节流还是字符流,都可以按照以下方式进行
* (1) 使用file类找到一个文件
* (2) 通过file类的对象去实例化字节流或字符流的子类。
* (3) 进行字节(字符)的读写操作。
* (4) 关闭文件流。
* */
public static void main(String[] args) {

File f = new File("D:\\temp1.txt");//通过File类找到D盘下的temp1.txt文件
Writer out = null;//声明输入字符流

try{
out = new FileWriter(f);//通过File类对象实例化Writer类对象
}catch(IOException e){
e.printStackTrace();
}

String str = "Hello World!!!";

try{
out.write(str);//调用Writer类的write方法,将str数组写到文件中
}catch(IOException e1){
e1.printStackTrace();
}

try{
out.close();//调用Writerl类的close()方法,关闭数据流操作
}catch(IOException e2){
e2.printStackTrace();
}

//一下为读文件操作
Reader in = null;//声明读字符流

try{
in = new FileReader(f);//通过File类的对象实例化Reader类对象
}catch(IOException e3){
e3.printStackTrace();
}

char c1[] = new char[1024];//开辟一个空间用于接收文件读进来的数据
int i = 0;

try{
i = in.read(c1);//将c1的引用传到read()方法之中,同时此方法返回读入数据的个数
}catch(IOException e4){
e4.printStackTrace();
}

try{
in.close();//调用Reader类的close()方法,关闭读字符流
}catch(IOException e5){
e5.printStackTrace();
}

System.out.println(new String(c1,0,i));//将字符串转化成数组输出
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: