IO基础------------------------------字符输出输入流

/*
 *   字符输出流
 *     java.io.Writer 所有字符输出流的超类
 *   写文件,写文本文件
 *   
 *   写的方法 write
 *     write(int c) 写1个字符
 *     write(char[] c)写字符数组
 *     write(char[] c,int,int)字符数组一部分,开始索引,写几个
 *     write(String s) 写入字符串
 *     
 *   Writer类的子类对象 FileWriter
 *   
 *   构造方法:  写入的数据目的
 *     File 类型对象
 *     String 文件名
 *     
 *   字符输出流写数据的时候,必须要运行一个功能,刷新功能
 *   flush()

 */

public class WriterDemo {
	public static void main(String[] args) throws IOException{
		FileWriter fw = new FileWriter("c:\\1.txt");
		
		//写1个字符
		fw.write(100);
		fw.flush();
		
		//写1个字符数组
		char[] c = {'a','b','c','d','e'};
		fw.write(c);
		fw.flush();
		
		//写字符数组一部分
		fw.write(c, 2, 2);
		fw.flush();
		
		//写如字符串
		fw.write("hello");
		fw.flush();
		
		fw.close();
	}
}
/*
 *  字符输入流读取文本文件,所有字符输入流的超类
 *    java.io.Reader
 *  专门读取文本文件
 *  
 *  读取的方法 : read()
 *   int read() 读取1个字符
 *   int read(char[] c) 读取字符数组
 *   
 *   Reader类是抽象类,找到子类对象 FileReader
 *   
 *   构造方法: 绑定数据源
 *     参数:
 *        File  类型对象
 *        String文件名

 */

public class ReaderDemo {
	public static void main(String[] args) throws IOException{
		FileReader fr = new FileReader("c:\\1.txt");
		/*int len = 0 ;
		while((len = fr.read())!=-1){
			System.out.print((char)len);
		}*/
		char[] ch = new char[1024];
		int len = 0 ;
		while((len = fr.read(ch))!=-1){
			System.out.print(new String(ch,0,len));
		}
		
		fr.close();
	}
}

专门对付文本文件的流

/*
 *  字符流复制文本文件,必须文本文件
 *  字符流查询本机默认的编码表,简体中文GBK
 *  FileReader读取数据源
 *  FileWriter写入到数据目的
 */

public class Copy_2 {
	public static void main(String[] args) {
		FileReader fr = null;
		FileWriter fw = null;
		try{
			fr = new FileReader("c:\\1.txt");
			fw = new FileWriter("d:\\1.txt");
			char[] cbuf = new char[1024];
			int len = 0 ;
			while(( len = fr.read(cbuf))!=-1){
				fw.write(cbuf, 0, len);
				fw.flush();
			}
			
		}catch(IOException ex){
			System.out.println(ex);
			throw new RuntimeException("复制失败");
		}finally{
			try{
				if(fw!=null)
					fw.close();
			}catch(IOException ex){
				throw new RuntimeException("释放资源失败");
			}finally{
				try{
					if(fr!=null)
						fr.close();
				}catch(IOException ex){
					throw new RuntimeException("释放资源失败");
				}
			}
		}
	}
}
假如用字符流的复制文件,例如图片,压缩包的话,会导致文件损坏,个人目前理解是字符拼接错位了(纯属自己瞎想)

猜你喜欢

转载自blog.csdn.net/jiulanhao/article/details/80837928