代码改变世界

字节流,字符流

2017-12-31 14:42  澄序源  阅读(178)  评论(0编辑  收藏  举报

字节流

File file = new File("C:\\0928\\test\\aaa_new.txt"); // 实例化一个流  传入地址(文件位置)
		File file_out = new File("C:\\0928\\test\\aaa_new_out.txt"); // 实例化一个流  传入地址(文件位置)
		// 输入流
		InputStream in = null; // 字节输入流
		OutputStream out = null; // 字节输出流
		int result = -1;
		try {
			in = new FileInputStream(file); // 读取本地字节数据
			out = new FileOutputStream(file_out); // 输出本地字节数据

			while ((result = in.read()) != -1) {
				// in.read() 判断是否输入完毕 完毕后 返回值为-1;
				System.out.print((char) result);// unicode
				out.write(result);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 一定会执行的代码 放在 finally 里
			try {
				in.close(); // 关闭
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

 字符流

File file = new File("c:\\0928\\test\\aaa_new.txt");
		File fileout = new File("c:\\0928\\test\\aaa_new_writer_out.txt");
		int result = -1;
		try {
			//字符流 , 一次读取2字节
			Reader reader = new FileReader(file); // 输入
			Writer writer = new FileWriter(fileout); // 输出
			while ((result = reader.read()) != -1) {
				System.out.print((char)result);
				writer.write(result);
			}
			reader.close();
			writer.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}