IO流 字符流拷贝

1 读取文件字符并打印:

public class Demo01 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//创建源
		File src =new File("E:/xp/test/a.txt");
		//选择流
		Reader reader =null;
		try {
			reader =new FileReader(src);
			//读取操作
			char[] flush =new char[1024];
			int len =0;
			while(-1!=(len=reader.read(flush))){ // 
				//字符数组转成 字符串
				String str =new String(flush,0,len);
				System.out.println(str);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("源文件不存在");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件读取失败");
		}finally{
			try {
				if (null != reader) {
					reader.close();
				}
			} catch (Exception e2) {
			}
		}
	}

}

2 文件拷贝:

public class CopyFileDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//创建源 仅限于 字符的纯文本
		File src =new File("E:/xp/test/Demo03.java");
		File dest =new File("e:/xp/test/char.txt");
		//选择流
		Reader reader =null;		
		Writer wr =null;
		try {
			reader =new FileReader(src);
			wr =new FileWriter(dest);
			//读取操作
			char[] flush =new char[1024];
			int len =0;
			while(-1!=(len=reader.read(flush))){ // 注意,要把数据读到 flush容器中 
				wr.write(flush, 0, len);
			}
			wr.flush();//强制刷出
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("源文件不存在");
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("文件读取失败");
		}finally{
			try {
				if (null != wr) {
					wr.close();
				}
			} catch (Exception e2) {
			}
			try {
				if (null != reader) {
					reader.close();
				}
			} catch (Exception e2) {
			}
		}
	
	}

}

猜你喜欢

转载自chengjianxiaoxue.iteye.com/blog/2400604