导航

读取,写文件

Posted on 2012-11-16 16:04  阿里大盗  阅读(179)  评论(0)    收藏  举报

1. File file = new File("C:/xxx.tct");  //创建一个file对象    2. 读取文件:     【】   FileInputStream fis = new FileInputStream(file);

    fis方法介绍:        (1)int i = fis.read(); //读取xxx.txt文件的第一个字节,并以ascii码数值表示;若文件txt为空,则返回-1。(例:txt文件中首字节为"a",则i=97)       (2)public int read(byte[] b)  //本方法是以字节为单位,来读取文件中的内容。并将读到的内容以ascii码保存在字节数组b中,所以b的大小决定了可以读取多少内容。                                   特别说明:本方法的返回值不一定要获取。当文件为空时,方法返回值是-1;当文件不为空时,返回值是min(b.length,文件的字节数) 。       使用实例:byte[] b = new byte[20]; //设定要从txt文件中读取多少个字节数                 fis.read(b);  //文件中的前20个字节被转换成ascii码保存进b中                 for(int i=0;i<b.length;i++){                     System.out.println(b[i]);}  //遍历输出b中的内容

 ☆ 小结:FileInputStream类可以直接封装file对象,但是它的方法都是以字节为单位读取文件内容并转换成ascii码,所以外层需要封装其他类。

【】    FileReader fr = new FileReader(file);

        与下面InputStreamReader2层封装类等效。(? 因为FileReader是InputStreamReader的子类,继承其方法)

           【】    InputStreamReader isr = new InputStreamReader(new FileInputStream(file),"GBK");

        isr方法介绍:            (1)isr.read();  //与fis的read方法类似,只不过是以双字节为单位来读取文件中的内容(双字节适合中文),但是本方法也是将内容转换成ascii码。

 ☆ 小结:(1)InputStreamReader类是以双字节为单位读取文件内容(适合中文),但是由于也会将内容转换成ascii码,所以外层需要封装其他类。           (2)如果文件内容中有中文,那么必须有2层嵌套:new InputStreamReader(new FileInputStreamReader(file));并且外层还需要一层类,以便于文件内容以非ascii码 

             的正常方式读出。

  【】    最外层的推荐封装类:

        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK")); //当txt为ANSI时,使用GBK;当txt为UTF-8时,使用UTF-8。         br.readLine(); //读取一行文件中的内容         br.readLine(); //再读取一行文件中的内容

 ● 总结:从c:/count1.txt中读取内容,并输出到屏幕上:(文件格式为ANSI)

        public static void main(String[] args){  File file = new File("c:/count1.txt");  try {   BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),"GBK"));      String s = br.readLine();   StringBuffer sb = new StringBuffer();   while(s!=null){    sb.append(s+"\n");    s = br.readLine();   }   System.out.println(sb);  } catch (FileNotFoundException e) {   e.printStackTrace();  } catch (IOException e) {   e.printStackTrace();  }}

     } 

3. 写入文件:

【】 public static void main(String[] args){          BufferedWriter bw = new BufferedWriter(new FileWriter(file)); //本句代码执行后,如果对应路径下没有file文件,会自动创建          bw.write("hello");           bw.flush();  //本句代码不可省略,否则内容无法写入文件中          bw.close();      } }