首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >特别要检查Java文件操作相关方法的返回值

特别要检查Java文件操作相关方法的返回值

作者头像
jeremyxu
发布2018-05-09 17:46:53
发布2018-05-09 17:46:53
1.3K0
举报

今天遇到一个很狗血的问题,一个功能在开发环境没有问题,但在生产环境出错了。

代码如下:

代码语言:javascript
复制
...
File tmpFile = new File(fileTmpPath);
File newFileTarget = new File(filePath);
tmpFile.renameTo(newFileTarget);
// 修改新文件的权限
FileManageHelper.chmod(newFileTarget);
....

最后报错信息提示执行chmod命令失败,但这个代码在开发环境没有问题啊。

仔细查找原因发现jdk的renameTo方法介绍如下:

代码语言:javascript
复制
/**
     * Renames the file denoted by this abstract pathname.
     *
     * <p> Many aspects of the behavior of this method are inherently
     * platform-dependent: The rename operation might not be able to move a
     * file from one filesystem to another, it might not be atomic, and it
     * might not succeed if a file with the destination abstract pathname
     * already exists.  The return value should always be checked to make sure
     * that the rename operation was successful.
     *
     * <p> Note that the {@link java.nio.file.Files} class defines the {@link
     * java.nio.file.Files#move move} method to move or rename a file in a
     * platform independent manner.
     *
     * @param  dest  The new abstract pathname for the named file
     *
     * @return  <code>true</code> if and only if the renaming succeeded;
     *          <code>false</code> otherwise
     *
     * @throws  SecurityException
     *          If a security manager exists and its <code>{@link
     *          java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
     *          method denies write access to either the old or new pathnames
     *
     * @throws  NullPointerException
     *          If parameter <code>dest</code> is <code>null</code>
     */
The rename operation might not be able to move a file from one filesystem to another

也就是说如果文件是从一个文件系统将文件move到另一个文件系统有可能失败,正好开发环境上tmpFilenewFileTarget在同一个文件系统中,而在生产环境中由于HA方案的原因这两个文件在不同的文件系统。

教训:一定要检查File的相关操作的返回值,如setLastModified, setReadOnly, setWritable, setReadable, setExecutable, createNewFile, delete, mkdir, mkdirs

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2014-03-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档