• 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中获取字符串

    中文乱码,不推荐

    只有把命运掌握在自己手中,从今天起开始努力,即使暂时看不到希望,也要相信自己。因为比你牛几倍的人,依然在努力。
  • 相关阅读:
    Session 0 隔离
    在DIV容器中使用浮动元素
    Linq学习总结(5)——标准查询运算符
    Linq学习总结(3)——yield
    消息拦截的简单实现
    网站内容可访问性——关于背景与前景颜色的对比标准
    CSS优先级
    Linq学习总结(4)——Lambda表达式
    element ui表格的校验和自定义校验规则
    vue 递归组件的两种方法
  • 原文地址:https://www.cnblogs.com/freesky168/p/14358180.html
Copyright © 2020-2023  润新知