使用常见OpenOption组合的最快方法

 prince小乀朱 发布于 2023-02-09 13:44

是否有一种简洁,惯用的方式(可能使用Apache Commons)来指定OpenOption的常见组合 StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING

2 个回答
  • 这些都是您的轻松可能性.

    静态导入,以提高可读性:

    import static java.nio.file.StandardOpenOption.CREATE_NEW;
    import static java.nio.file.StandardOpenOption.WRITE;
    
    OpenOption[] options = new OpenOption[] { WRITE, CREATE_NEW };
    

    使用默认值:

         //no Options anyway
         Files.newBufferedReader(path, cs)
    
         //default: CREATE, TRUNCATE_EXISTING, and WRITE not allowed: READ
         Files.newBufferedWriter(path, cs, options)
    
         //default: READ not allowed: WRITE
         Files.newInputStream(path, options)
    
         //default: CREATE, TRUNCATE_EXISTING, and WRITE not allowed: READ
         Files.newOutputStream(path, options)
    
         //default: READ do whatever you want
         Files.newByteChannel(path, options)
    

    最后,可以指定这样的选项集:

         Files.newByteChannel(path, EnumSet.of(CREATE_NEW, WRITE));
    

    2023-02-09 13:45 回答
  • 我能提供的最好的建议是欺骗T ...和T []的等价,其中一个其他stackoverflow讨论说应该工作

    我可以将数组作为参数传递给Java中带有变量参数的方法吗?

    所以...

    OpenOption myOptions[] = {StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING};
    OutputStream foo=OutputStream.newOutputStream(myPath,myOptions);
    

    警告:未经测试.

    2023-02-09 13:45 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有