在项目中要对大量的文件操作,而且对性能方面要求比较高,当把程序发布到Unix上过程中发现很多问题。
比如
File f =new File("/home/ids/dep.log.20121210"); System.out.println("canWrite="+f.canWrite()); System.out.println("setReadOnly="+f.setReadOnly()); System.out.println("canWrite="+f.canWrite()); System.out.println("canRead="+f.canRead());
设置为f.setReadOnly();
canWrite=true这里我就有点想不明白了。java.io.File 有很多方法都是native 方法。都是跟平台有关系的。主要的实现还是在class Win32FileSystem extends FileSystem { } protected native boolean delete0(File f); public synchronized native boolean deleteOnExit(File f); public native String[] list(File f); public native boolean createDirectory(File f); public boolean rename(File f1, File f2) { // Keep canonicalization caches in sync after file deletion // and renaming operations. Could be more clever than this // (i.e., only remove/update affected entries) but probably // not worth it since these entries expire after 30 seconds // anyway. cache.clear(); prefixCache.clear(); return rename0(f1, f2); } protected native boolean rename0(File f1, File f2); public native boolean setLastModifiedTime(File f, long time); public native boolean setReadOnly(File f);然后把jdk的源码给下下来看看。native 方法是怎么实现的。JNIEXPORT jboolean JNICALLJava_java_io_Win32FileSystem_createDirectory(JNIEnv *env, jobject this, jobject file){ jboolean rv = JNI_FALSE; WITH_NATIVE_PATH(env, file, ids.path, path) { if (mkdir(path) == 0) { rv = JNI_TRUE; } } END_NATIVE_PATH(env, path); return rv;}JNIEXPORT jboolean JNICALLJava_java_io_Win32FileSystem_rename0(JNIEnv *env, jobject this, jobject from, jobject to){ jboolean rv = JNI_FALSE; WITH_NATIVE_PATH(env, from, ids.path, fromPath) { WITH_NATIVE_PATH(env, to, ids.path, toPath) { if (rename(fromPath, toPath) == 0) { rv = JNI_TRUE; } } END_NATIVE_PATH(env, toPath); } END_NATIVE_PATH(env, fromPath); return rv;}<noscript></noscript>
renameTo
public boolean renameTo (File dest)
重新命名此抽象路径名表示的文件。此方法行为的许多方面都是与平台有关的:重命名操作无法将一个文件从一个文件系统移动到另一个文件系统,该操作不是不可分的,如果已经存在具有目标抽象路径名的文件,那么该操作可能无法获得成功。应该始终检查返回值,以确保重命名操作成功。
参数:dest
- 指定文件的新抽象路径名 返回: 当且仅当重命名成功时,返回 true
;否则返回 false
抛出: SecurityException
- 如果存在安全管理器,且其 SecurityManager.checkWrite(java.lang.String)
方法拒绝对原路径名和新路径名进行写访问 NullPointerException
- 如果参数 dest
为 null
可以看到在renameTo方法中底层实现是通过c的rename方法实现的。不错,多看看源码有利于提高啊。