码迷,mamicode.com
首页 > 编程语言 > 详细

java文件读写

时间:2017-12-28 14:37:35      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:cep   print   gbk   amr   class   简单   throws   static   cat   

IO流简单来说就是输入流和输出流主要是用来处理设备之间的数据传输

案例1采用的是字节流方式,案例2采用字符流方式;字节流和字符流之间差异很大,读者需根据自己的场景使用

 

案例1:

  采用字节流和包装流(读者可自行了解包装流,主要采用的是装饰器模式)的方式进行文件读写

public class FileCopy {
    
    public static void copyfile(File src,File res) throws Exception{
        InputStream in=new BufferedInputStream(new FileInputStream(src));
        OutputStream out=new BufferedOutputStream(new FileOutputStream(res));
         byte[] bt=new byte[1024];
        while(-1!=(in.read(bt))){
            out.write(bt, 0, bt.length);
        }
        out.flush();
        out.close();
        in.close();
    }
    
    public static void main(String[] args) {
        File src=new File("D:/tmp/test.xls");
        File res=new File("D:/tmp/b.xls");
        try {
            copyfile(src, res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 

案例2:

  采用包装流和字符流进行文件读写

public class FileCopy {
    public static void main(String[] args) throws Exception {
        BufferedReader br=new BufferedReader(
                new InputStreamReader(
                        new BufferedInputStream(
                                new FileInputStream(new File("d:/tmp/a.txt"))),"GBK"));
        
        BufferedWriter out=new BufferedWriter(
                new OutputStreamWriter(
                        new BufferedOutputStream(
                                new FileOutputStream(new File("d:/tmp/b.txt"))),"GBK"));
        String line=null;
        while(null!=(line=br.readLine())){
            out.write(line);
            out.newLine();
        }
        out.flush();
        out.close();
        br.close();
    }
}

 

java文件读写

标签:cep   print   gbk   amr   class   简单   throws   static   cat   

原文地址:https://www.cnblogs.com/weishao-lsv/p/8135462.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!