Java I/O 解读与使用实例

Java I/O解读与使用实例

I/O理解图片
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述


字节输入流

代码演示

package com.lilin.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * <p>字节输入流</p>
 * 
 * 字节流读取文件内容
 * 读取中文内容会乱码
 * <p>(½ñÌìÊǸöºÃÌìÆø£¬do you know how much i love you?)</p>
 * 
 * @author lilin 2015年10月13日上午10:31:56
 * @since JDK 1.6
 */
public class InputStreamTest {

    public static void main(String[] args) {
        String path = "D:"+File.separator+"aaa.txt";
        readFile1(path);
        readFile2(path);
    }

    /**
     * 单个字符读取文件
     * @param path
     */
    public static void readFile1(String path){
        FileInputStream is = null;
        try {
            is = new FileInputStream(path);
            System.out.println("==========单个字符读取begin========");
            int ch = 0;
            while ((ch = is.read()) != -1) {
                System.out.print((char)ch);
            }
            System.out.println(); 
            System.out.println("==============单个字符读取end===========");  
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
        }


    }

    /**
     * 字节流读取文件:数组循环读取 
     */
    public static void readFile2(String path){
        FileInputStream is = null;
        try {
            //创建文件输入流对象
            is = new FileInputStream(path);
            //设定读取的字节数
            int n = 1024;
            byte buffer[] = new byte[n];
            //读取输入流
            System.out.println("--------数组循环读取 begin--------");
            while (is.read(buffer,0,n) !=-1 &&(n>0)) {
                System.out.print(new String(buffer));
            }
            System.out.println();
            System.out.println("--------数组循环读取 end--------");
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            //关闭输入流
            if (is != null) {
                try {
                    is.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }

    } 

}

字节输出流

代码演示

package com.lilin.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * <p><b>功能概要:</b>字节输出流</p>
 * 
 * 按字节流写文件 FileInputStream和FileOutputStream 提供读写操作功能
 * @author lilin 2015年10月13日上午10:54:16
 * @since JDK 1.6
 */
public class OutputStreamTest {

    public static void main(String[] args) {
        String input = "D:" +File.separator+ "image.png";//图片路径
        String output = "D:" +File.separator+ "copyImage.png";//读写(复制文件)后存放路径
        writeFile(input, output);
    }

    public static void writeFile (String input,String output) {
        FileInputStream fis = null;//文件读取
        FileOutputStream fos = null;//文件写出
        byte[] buffer = new byte[100];
        int tmp = 0;
        try {
            fis = new FileInputStream(input);
            fos = new FileOutputStream(output);
            //读写操作循环
            while (true) {
                tmp = fis.read(buffer, 0, buffer.length);//将image.png文件读取到FileInputStream当中
                //条件判断,当文件为空时,跳出
                if (tmp == -1){
                    break;
                }
                fos.write(buffer, 0, tmp);//将读取好的文件写出来
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭读写操作流
                fis.close();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

字符输入流

代码演示

package com.lilin.io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;


/**
 * 功能概要: 字符流  文件读写操作
 * @author lilin 2015年10月13日下午3:23:12
 * @since JDK 1.6
 */
public class ReaderTest {

    public static void main(String[] args) {
        String path = "D:" + File.separator + "hello.txt";
        readFile1(path);
        readFile2(path);
        readFile3(path,"UTF-8");

    }

    /**
     * 字符流读取文件1
     * @param path
     */
    public static void readFile1(String path) {
        FileReader reader = null;
        try {
            reader = new FileReader(path);//新建读文件
            char[] buf = new char[1024];
            int temp = 0;
            System.out.println("------------字符流读取文件方法一---------------");
            while ((temp = reader.read(buf)) != -1) {
                System.out.print(new String(buf, 0, temp));
                System.out.println();
            }
        } catch (IOException e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 字符流读取文件2
     * @param path
     */
    public static String readFile2 (String path){
        File file = new File(path);
        StringBuffer sb = new StringBuffer();
        if (file.isFile()) {
            BufferedReader bufferedReader = null;//新建文件读写缓存
            FileReader  fileReader = null;
            try {
                fileReader = new FileReader(file);
                bufferedReader = new BufferedReader(fileReader);

                //读取一个文本行。通过下列字符之一即可认为某行已终止:换行 ('\n')、回车 ('\r') 或回车后直接跟着换行。
                String line = bufferedReader.readLine(); 
                System.out.println("----------字符流读取文件方法二-----------------");
                while ( line !=null) {
                    System.out.println(line);
                    sb.append(line+"\r\n");
                    line = bufferedReader.readLine();
                }
            } catch (FileNotFoundException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                    e.printStackTrace();
            } finally {
                try {
                    fileReader.close();
                    bufferedReader.close();
                } catch (Exception e2) {
                    // TODO: handle exception
                }
            }

        }
        return sb.toString();

    }

    /**
     * 字符流读取文件3
     * 
     *<p>可以指定文件编码格式</p> 
     * @param path
     */
    public static String readFile3 (String path,String charset){
        File file = new File(path);
        StringBuffer buffer = new StringBuffer();
        if (file.isFile()) {
            BufferedReader bufferedReader = null;
            InputStreamReader inputStreamReader = null;
            try {
                inputStreamReader = new InputStreamReader(new FileInputStream(file), charset);//读入
                bufferedReader = new BufferedReader(inputStreamReader);//写出
                String line = bufferedReader.readLine();
                System.out.println("------------字符流读取文件三-----------------");
                while (line != null) {
                    System.out.println(line);
                    buffer.append(line+"\r\n");
                    line = bufferedReader.readLine();
                }
            } catch (FileNotFoundException e) {
                    e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStreamReader.close();
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return buffer.toString();
    }

}

字符输出流

代码演示

package com.lilin.io;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 功能概述:按字符写入
 * 
 * @author lilin 2015年10月13日下午5:38:11
 * @since JDK 1.6
 */
public class WriterTest {

    public static void main(String[] args) {
        String path = "D:" + File.separator + "helloaaa.txt";
        String str = "Rockli哈哈哈哈RockLi真帅\r\n";
         writeFile(path,str); 

    }

    public static void writeFile(String path, String content){
        //由于IO操作会抛出异常,因此在try语句块的外部定义FileWriter的引用  
        FileWriter writer = null;
        try {
            //以path为路径创建一个新的FileWriter对象  
             //如果需要追加数据,而不是覆盖,则使用FileWriter(path,true)构造方法  
            writer = new FileWriter(path,true);
              //将字符串写入到流中,\r\n表示换行  
            writer.write(content);
            //如果想马上看到写入效果,则需要调用w.flush()方法 
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //如果前面发生异常,那么是无法产生w对象的  
            //因此要做出判断,以免发生空指针异常  
            if (writer != null) {
                try {
                     //关闭流资源,需要再次捕捉异常  
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

原文转载至:http://blog.csdn.net/evankaka/article/details/48225085#t4



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值