JAVA小练习144——输入输出字符流的练习

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

public class Demo144 {
	
	public static void main(String[] args) throws IOException {
//		 readTest();
		readTest2();
		writerTest();
	}
	
	
	//方式二:使用缓冲字符数组读取文件的数据
	public static void readTest2() throws IOException{
		//找到目标文件
		File file = new File("E:\\约翰克里斯朵夫.txt");
		//建立数据的输入通道
		FileReader fileReader = new FileReader(file);
		//建立缓冲字符数组,读取文件的数据
		char[] buf = new char[1024];
		int length = 0; 
		while((length = fileReader.read(buf))!=-1){  // read(char[] buf) 读取到的字符数组存储到了字符数组中,返回了本次读取到的字符个数。 
			System.out.print(new String(buf,0,length));
		}
		//关闭资源
		fileReader.close();
	}
	
	

	//方式一:每次只会读取一个字符的数据
	public static void readTest() throws IOException{
		//找到目标对象
		File  file = new File("f:\\a.txt");
		//建立数据的输入通道
		FileReader fileReader = new FileReader(file);
		//读取文件数据
		int content= 0;
		while((content=fileReader.read())!=-1){   // FileReader的read()方法每次读取一个字符的数据,如果读到 了文件末尾返回-1表示。 
			System.out.print((char)content);
		}
		//关闭资源
		fileReader.close();
	}
	
	
	public static void writerTest() throws IOException{
		//找到目标文件
		File  file = new File("F:\\a.txt");
		//建立数据 的输出通道
		FileWriter fileWriter = new FileWriter(file); //第二个参数为true的意义是指追加数据。
		//准备数据,把数据写出
		String data = "现在雨停了";
		fileWriter.write(data);
		
		//刷新输出字符流
		fileWriter.close();
		
	}
	
	
	
}






猜你喜欢

转载自blog.csdn.net/Eric_The_Red/article/details/92407933