java字符流,字符逐个读取和写入

时间:2021-07-08 16:17:03
package cwj.bbb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;



class App
{
public static void main(String[] args) throws IOException
{
/*
* 把这个路径下的文件/home/cwjy1202/FoodMart.xml
* 以字符流的方式逐个字符读取到/home/cwjy1202/hadoop/javaTest/foodmart0.txt
* */
File file = new File("/home/cwjy1202/FoodMart.xml");
Reader fr = new FileReader(file);
Writer fw = new FileWriter("/home/cwjy1202/hadoop/javaTest/foodmart0.txt", false);

//逐个字符读取
int len = fr.read();
while (-1 != len)
{
//逐个写入
fw.write(len);
//System.out.printf("%c", len);
len = fr.read();
}

//把缓冲区的数据强行输出。因为读完了,不一定会写完,
//所以最好采用flush,直接关闭流,可能会数据丢失
fw.flush();
fw.close();
fr.close();

}
}