IO基础--OutputStream·FileWriter的基本用法

来源:互联网 发布:dropbox 类似软件 编辑:程序博客网 时间:2024/06/05 11:22

     基础文章,仅供自己以及初学者参考。(我其实不算初学者,哈哈)主要是android开发中常常需要记录log,这部分当初学的的时候没学清楚,平时都是搬砖过来直接用。今天有时间就看了一下这部分。

IO包下的基本结构首先需要了解一下,今天涉及到的5个类File、OutputStream、InputStream、Writer、Reader。想详细了解自己可以查,我这里不做细讲,这里主要介绍一下file输入输出。

      现在记录一个log文件的生成过程:

      1.文件生成

      

   String pathname="D:"+File.separator+"LogDir";            File file=new File(pathname);            if(!file.exists()){            file.mkdirs();            }            File text=new File(file, "Log.txt");            if (!text.exists()) {text.createNewFile(); }    

           文件生成这里我建议可以和io分开记,因为File类只负责文件的生成,生成过程如上:我们这里在D://LogDir文件夹下创建一个Log.txt的文本。当然可以写成File file=new File(”D://LogDir/Log.txt“); 我建议第一种写法,一个负责路径,一个负责文件名,新手看起来清晰一些。有了文件才能进行后面的文件输入输出工作。

          2.输出log

                a.FileWriter(text为1中的file文件)


private static void StringOut(File text) throws IOException {FileWriter fw=new FileWriter(text);String log="输出了log到文本文件";fw.write(log);fw.close();}
               b.FileOutputStream

private static void OutText(File text) throws IOException {

FileOutputStream fos=new FileOutputStream(text);byte[] b="输出了log到文本文件".getBytes();fos.write(b);fos.close();}
               以上是分别以字符流和字节流输出的实例(函数名请自动忽略),不使用try...catch是不是看起来简介多了?

3.输入log

a.FileReader(为什么转成BufferedReader?因为我想用readLine()方法,但是FileReader没找到)

private static void StringIn(File file) throws IOException {FileReader fr=new FileReader(file);BufferedReader br=new BufferedReader(fr);String s;while((s=br.readLine())!=null){System.out.println(s);}fr.close();br.close();}

              b.FileInputStream

private static void InText(File text) throws IOException { FileInputStream fis=new FileInputStream(text);         byte[] buffer=new byte[512];         int len; while((len=fis.read(buffer))!=-1){  System.out.println(new String(buffer,0,len));  }         fis.close();}
              以上分别是字符流和字节流的输入。

               关于字节流和字符流的区别,字节是一个byte一个byte的读,字符流是一个字符一个字符的读。废话么?嘿,一个汉字在编码下占16bit,即2个byteW;但是他只是一个字符。所以在读取字符的情况下,它们大概就这点区别。对于不喜欢用数组的同学,大概会比较喜欢FileReader和Write吧


0 0
原创粉丝点击