易截截图软件、单文件、免安装、纯绿色、仅160KB

请慎用java的File#renameTo(File)方法

以前我一直以为File#renameTo(File)方法与OS下面的 move/mv 命令是相同的,可以达到改名、移动文件的目的。不过后来经常发现问题:File#renameTo(File)方法会返回失败(false),文件没有移动,又查不出原因,再后来干脆弃用该方法,自己实现一个copy方法,问题倒是再也没有出现过。
昨天老板同学又遇到这个问题,File#renameTo(File)方法在windows下面工作的好好的,在linux下偶尔又失灵了。回到家我扫了一遍JDK中File#renameTo(File)方法的源代码,发现它调用的是一个本地的方法(native method),无法再跟踪下去。网上有人说该方法在window下是正常的,在linux下面是不正常的。这个很难说通,SUN不可能搞出这种平台不一致的代码出来啊。
后面在SUN的官方论坛上看到有人提到这个问题“works on windows, don't work on linux”,后面有人回复说是“file systems”不一样。究竟怎么不一样呢?还是没有想出来...
后面在一个论坛里面发现了某人关于这个问题的阐述:
引用
In the Unix'esque O/S's you cannot renameTo() across file systems. This behavior is different than the Unix "mv" command. When crossing file systems mv does a copy and delete which is what you'll have to do if this is the case.
The same thing would happen on Windows if you tried to renameTo a different drive, i.e. C: -> D:
终于明白咯。
做个实验:
Java代码
  
File sourceFile = new File("c:/test.txt");   
File targetFile1 = new File("e:/test.txt");   
File targetFile2 = new File("d:/test.txt");   
System.out.println("source file is exist? " + sourceFile.exists()   
    + ", source file => " + sourceFile);   
System.out.println(targetFile1 + " is exist? " + targetFile1.exists());   
System.out.println("rename to " + targetFile1 + " => "  
    + sourceFile.renameTo(targetFile1));   
System.out.pr


相关文档:

JNA实现Java调用Fortran

在成功实现Java调用C++之后,接下来想到能否通过JNA实现Java调用Fortran,今天试验了一下,还是比较容易的。
网上有一个Java调用F95的例子,但是我考虑不仅要实现F95的调用,还要实现F77的调用,所以费了一些周折。
问题的关键在于F77为过程名自动添加了一个尾部的下划线,所以sub1这个过程,到Java一端,就变成了sub1_, ......

IBM FileNet Content Java API 简介

2008 年 6 月 24 日
原文地址: http://www.ibm.com/developerworks/cn/data/library/techarticles/dm-0806wangys/
本文介绍 IBM FileNet P8 4.0 Platform 提供的 Content Java API。首先对 FileNet P8 Content Engine 和 API 进行概要介绍, 并说明了一些基本概念,随后详细介绍了 FileNet Content Engine提供的基于 EJB ......

java Map 遍历方法

第一种:效率高
Map map = new HashMap();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Object key = entry.getKey();
Object val = entry.getValue();
}
第二种:效率低,以后尽量少使用!
Map map = new HashMap();
......

java 验证身份证 身份证java验证

引用于:http://blog.csdn.net/hhzxj2008/archive/2010/01/10/5171444.aspx
public static boolean validatePersonalId(String personalId) {

if ((personalId == null) || ((personalId.length() != 15) &&
(personalId.length() != 18))) {
return ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号