JavaIO字符流读写数据

【声明】本文参考自极客学院视频

1、字符流读文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class RWByCharStream {

	public static void main(String[] args) {
		
		try {
			File file=new File("java.txt");
			FileInputStream fis;
			fis = new FileInputStream(file);
			//将字节流转换为字符流
			InputStreamReader isr=new InputStreamReader(fis, "utf-8");
			char input[]=new char[100];
			int l=0;
			while ((l=isr.read(input))!=-1) {
				//会自动调用char数组的toString()方法
				//System.out.println(input);
				
				System.out.println(new String(input,0,l));
			}
			//关闭。
			//先打开的后关闭,后打开的先关闭
			isr.close();
			fis.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

2、字符流实现赋值文本文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class RWByCharStream {

	public static void main(String[] args) {
		
		try {
			//File file=new File("java.txt");
			FileInputStream fis=new FileInputStream("java.txt");
			FileOutputStream fos=new FileOutputStream("java_new.txt");
			InputStreamReader isr=new InputStreamReader(fis, "utf-8");
			OutputStreamWriter osw=new OutputStreamWriter(fos,"utf-8");//对同一个文件的读写编码方式要一致
			
			char input[]=new char[100];
			int l=0;
			while ((l=isr.read(input))!=-1) {
				String inputString=new String(input,0,l);
				osw.write(input,0,l);
			}

			osw.close();
			fos.close();
			isr.close();
			fis.close();
			System.out.println("done");
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		


	}

}

你可能感兴趣的:(#,JavaSE入门)