首页 » Java » Java IO操作

Java IO操作

原文 http://blog.csdn.net/MakeContral/article/details/78212348

2017-10-12 12:20:25阅读(495)

前几天碰到一个IO程序,发现在使用上忘得差不多了,这里写几个demo便宜回顾一下。

字符流 FileReader/FileWriter demo
public static void main(String[] args){
        try {
            FileReader fileReader = new FileReader("E:\\test.txt");
            FileWriter fileWriter = new FileWriter("D:\\newTest2.txt");
            char[] chars = new char[1024];
            int len = 0;
            while((fileReader.read(chars))!=-1){
                fileWriter.write(chars,0,len);
            }
            fileReader.close();
            fileWriter.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
BufferedReader/BufferedWriter demo
public static void main(String[] args){
try {
           FileWriter fileWriter = new FileWriter("E:\\test1111.txt");
           FileReader fileReader = new FileReader("E:\\test.txt");
           BufferedReader bufferedReader = new BufferedReader(fileReader);
           BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
           char[] chars = new char[1024];
           int len ;
           while((len=bufferedReader.read(chars))!=-1){
               bufferedWriter.write(new String(chars,0,len));
           }
           bufferedReader.close();
           bufferedWriter.close();
       }catch (IOException e){
           e.printStackTrace();
       }
    }
}
字节流 FileInputStream/FileOutputStream demo
public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("E:\\test.txt");
            FileOutputStream fos = new FileOutputStream("D:\\newTest.txt");
            byte[] bytes = new byte[1024];
            int len = 0;
            while( (len=fis.read(bytes))!=-1){
                fos.write(bytes,0,len);
            }
            fis.close();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
BufferedInputStream/BufferedOutputStream demo
public static void main(String[] args){
       BufferedInputStream bis =null;
       BufferedOutputStream bos = null;
       try {
           bis = new BufferedInputStream(new FileInputStream("E:\\test.txt"));
           bos = new BufferedOutputStream(new FileOutputStream("D:\\newTest1.txt"));
           int len = 0;
           byte[] bytes = new byte[1024];
           while((len=bis.read(bytes))!=-1){
               bos.write(bytes,0,len);
           }
       }catch (IOException e){
           e.printStackTrace();
       }finally {
           try {
               if(bos!=null) bos.close();
               if(bis!=null) bis.close();
           }
           catch (IOException e) {
               e.printStackTrace();
           }
       }
   }

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹