//Create the file. File file = new File(fileName); if (!file.exists()) file.createNewFile(); if (file.exists()) System.out.println("The file exists!"); if (file.canRead()) System.out.println("The file can be read!"); if (file.canWrite()) System.out.println("The file can be written!"); if (file.isFile()) System.out.println("It's a file!");
//Write to the created file. FileOutputStream out = new FileOutputStream(file); PrintStream p = new PrintStream(out); p.println("This is only a test!"); p.close();
//Read the information from that file. BufferedReader br = new BufferedReader(new FileReader(file)); StringBuffer sb = new StringBuffer(); while (true) { String sl = br.readLine(); if (sl == null) { break; } else { sb.append(sl + "\n"); } } br.close(); System.out.println("The content in the file:"); System.out.print("\t" + sb.toString());
//File rename File newfile = new File(renameFileName); if (newfile.exists()) System.out.println(renameFileName + "exsited"); else { if (file.renameTo(newfile)){ System.out.println("Rename sucessful!"); } else { System.out.println("Rename failed!"); } }
//delete file if (file.delete()) System.out.println("The old file deleted!"); if (newfile.delete()) System.out.println("The renamed file deleted!"); } catch (IOException e) { //Error happened e.printStackTrace(); System.out.println("Error occurs in writing to the file."); } }
Filename: E:\VerylongpathVerylongpathVerylongpath VerylongpathVerylongpathVerylongpathVerylongpathVer ylongpathVerylongpathVerylongpathVerylongpath\ VerylongpathVerylongpathVerylongpathVerylong pathVerylongpathVerylongpathVerylongpath VerylongpathVerylongpathVerylongpathVerylongpath.t xt File path length: 272 The file exists! The file can be read! The file can be written! It's a file! The content in the file: This is only a test! Rename sucessful! The renamed file deleted!
从微软官方网站 Path Field Limits ,可以查到,使用 Unicode 版本的 API,对于使用 NTFS 文件系统的 Windows NT 4.0, Windows 2000, Windows XP Home Edition, Windows XP Professional 和 Windows Server 2003 操作系统,可以支持 32768 字节的文件路径长度。同时,路径名必须使用 \?\ 的前缀。依照这个思路,我们设计了实验。
本文首先列出了不同的 JDK 版本在 Windows 操作系统上对于长路径名文件处理的区别,同时指出了 JDK 5.0 开始才完全支持长路径名;在第二部分中给出了两种支持长路径名文件的 C/C++ 编程方法。使用上文中的任一方法,我们都可以实现对长路径名文件的操作,这将在很大程度上方便我们的开发工作,解决在 Windows 平台上标准 API 函数对长路径名文件支持的局限性问题。
声明
以上实验代码仅在 Windows XP 操作系统和 VC.NET 编译环境中测试通过,作者不对其提供任何种类的保证。如果有任何问题,欢迎来信与作者讨论。
Reprint policy:
All articles in this blog are used except for special statements
CC BY 4.0
reprint policy. If reproduced, please indicate source
John Doe
!