zoukankan      html  css  js  c++  java
  • Java IO的常用方法

    文件复制

    1 使用IO复制

    public static void ioCopy(String pathIn,String pathOut) throws IOException {
        BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(pathIn));
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(pathOut));
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer,0,len);
        }
        inputStream.close();
        outputStream.close();
    }
    

    2 使用NIO复制

    public static void channelCopy(String pathIn, String pathOut) throws IOException {
        FileChannel fcIn = new FileInputStream(pathIn).getChannel(),
                fcOut = new FileOutputStream(pathOut).getChannel();
        fcIn.transferTo(0, fcIn.size(), fcOut);
        fcIn.close();
        fcOut.close();
    }
    

    向文件中写入字符

    1 用Writer向文件中写入字符串

    /**
    * @param content
    * @param path
    * @return void
    * @desc 用Writer向文件中写入字符串
    * @method stringToFileByWriter
    * @author YulinChen
    * @date 2020/2/13 20:12
    */
    public static void stringToFileByWriter(String content, String path) throws IOException {
       PrintWriter writer = new PrintWriter(new File(path));
       writer.print(content);
       writer.close();
    }
    

    2 用Channel向文件中写入字符串

    /**
    * @param content
    * @param path
    * @return void
    * @desc 用Channel向文件中写入字符串
    * @method stringToFileByChannel
    * @author YulinChen
    * @date 2020/2/13 20:12
    */
    public static void stringToFileByChannel(String content, String path) throws IOException {
       FileChannel channel = new FileOutputStream(path).getChannel();
       //FileChannel channel = new RandomAccessFile(path, "rw").getChannel();
       channel.write(ByteBuffer.wrap(content.getBytes("UTF-8")));
       channel.close();
    }
    

    从输入中获取字符串

    1 从流中获取字符串

    /**
    * @param in 输入流
    * @return java.lang.String
    * @desc 从流中获取字符串
    * @method getString
    * @author YulinChen
    * @date 2020/2/13 19:49
    */
    public static String getString(InputStream in) throws IOException {
       BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
       StringBuilder sb = new StringBuilder();
       for (String line = reader.readLine(); line != null; line = reader.readLine()) {
           sb.append(line).append("
    ");
       }
       reader.close();
       return sb.toString();
    }
    

    2 从Channel中获取字符串

    中文乱码,不推荐

    只有把命运掌握在自己手中,从今天起开始努力,即使暂时看不到希望,也要相信自己。因为比你牛几倍的人,依然在努力。
  • 相关阅读:
    微信小程序订阅消息
    自动生成小学四则运算题目
    个人项目作业
    自我介绍+软工5问
    软件工程之获小黄衫感言
    2020软件工程个人作业06——软件工程实践总结作业
    2020软件工程作业05
    2020软件工程作业00——问题清单
    2020软件工程作业04
    2020软件工程作业03
  • 原文地址:https://www.cnblogs.com/freesky168/p/14358180.html
Copyright © 2011-2022 走看看