java IO源(二)-使用字符方式读写文件
java IO流(二)----使用字符方式读写文件
前面采用字节流进行读取文件,现在采用字符方式进行文件的读写,主要是用到FileReader和FileWriter,他们都是继承了Reader和Writer两个基类,操作上和字节方式差不多,看代码。
package com.io; import java.io.*; public class ReaderOne { public static void main(String[] args) { //读取文本文件 FileWriter fw; int i; try { FileReader fr = new FileReader("D://java//a.txt"); int c; while((c=fr.read())!=-1) System.out.print((char)c); fr.close(); } catch (Exception e) { System.out.print("找不到文件"); } //写入文件 FileReader fr; try { fr = new FileReader("D://java//a.txt"); } catch (Exception e) { System.out.println("not found this file"); return; } try { fw = new FileWriter("D://java//b.txt"); } catch (Exception e) { // TODO: handle exception System.out.println("error"); e.printStackTrace(); return; } try { i = fr.read(); while(i!=-1) { fw.write(i); i=fr.read(); } fr.close(); fw.close(); } catch (Exception e) { System.out.print("写入出错"); } } }
什么时候使用字节什么时候采用字符方式呢,一般按照字面上来说,字符的长度是字节的2倍,如果是中文的话,用字符。
接下来将讲述如何进行两种方式之间的转换。