There are many things that can go wrong:

  • A class works in Unix but doesn't on Windows (or vice versa)
  • Invalid filenames due to double or missing path separators
  • UNC filenames (on Windows) don't work with my home-grown filename utility function

UNC (Universal Naming Convention)通用命名约定。windows目录或文件的 UNC 名称可以包括共享名称下的目录路径,格式为: \\servername\sharename\directory\filename。

一个在linux或windows移植的小技巧 System.getProperty("file.separator")

1.These are good reasons not to work with filenames as Strings. Using java.io.File instead handles many of the above cases nicely.

  String tmpdir = "/var/tmp";
String tmpfile = tmpdir + System.getProperty("file.separator") + "test.tmp";
InputStream in = new FileInputStream(tmpfile);

改为下面的代码会更好:

  File tmpdir = new File("/var/tmp");
File tmpfile = new File(tmpdir, "test.tmp");
InputStream in = new FileInputStream(tmpfile);

2.下面是一个不好的方法:

  public static String getExtension(String filename) {
int index = filename.lastIndexOf('.');
if (index == -1) {
return "";
} else {
return filename.substring(index + 1);
}
}

如果传入 "C:\Temp\documentation.new\README"则会返回"new\README"。但这不是我们想要的结果。

3.复制文件

 public void copyFile() throws IOException{
FileInputStream iStream = new FileInputStream(new File("a.txt"));
FileOutputStream oStream = new FileOutputStream(new File("acopy.txt"));
byte [] bytes = new byte[2048];
while(iStream.read(bytes) != -1){
oStream.write(bytes);
}
oStream.flush();
oStream.close();
iStream.close();
}
05-11 16:59