java的IO流初探

DEMO代码:

/*
 * 文件IO流的简单演示
 */
package com.IO;
import java.io.*;

public class Demo_IO_1
{
    
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        /*
        File file = new File("/javatest.txt");
        if(!file.exists())
        {
            try
            {
                file.createNewFile();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            File file2 = new File("F:\\ff");
            try
            {
                if(file2.isDirectory())
                {
                    
                }
                else 
                {
                    file2.mkdirs();
                    System.out.println("文件夹创建");
                }
            }
            catch (Exception e)
            {
                // TODO: handle exception
            }
        }
        */
        //读文件
        File file = new File("F:\\javatest.txt");
        //因为file没有读写能力,所以要定义一个inputstream。
        FileInputStream fis = null;
        try
        {
            fis =  new FileInputStream(file);
            //定义一个字节数组,相当于缓存
            byte []b = new byte[1024];
            int n = 0; //实际读取到的字符数
            //循环读取,一直读到文件尾
            while((n=fis.read(b)) != -1)
            {
                //把字节转成string
                String s = new String(b,0,n);
                System.out.println(s);
            }
            
        }
        catch (Exception e)
        {
            // TODO: handle exception
        }
        finally    //无论是否异常必须执行
        {
            //关闭文件流
            try
            {
                fis.close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }        
    //写文件
        File file2 = new File("F:\\writer.txt");
        FileOutputStream fos = null;
        try
        {
            fos = new FileOutputStream(file2);
            String string = "我是必胜\r\n我是最棒"; //返回换行\r\n
            fos.write(string.getBytes());
        }
        catch (Exception e)
        {
            // TODO: handle exception
        }
        finally
        {
            try
            {
                fos.close();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }    
}

代码实现的功能比较简单,就是字节流的读取和写入。

                    字节流(二进制)                字符流(文本文件)
输入          InputStream                     Reader
输出          OutputStream                   Writer
posted @ 2013-08-04 22:05  月之星狼  阅读(222)  评论(0编辑  收藏  举报