java.io.File实战

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.

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

改为下面的代码会更好:

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

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

1  public static String getExtension(String filename) {
2    int index = filename.lastIndexOf('.');
3    if (index == -1) {
4      return "";
5    } else {
6      return filename.substring(index + 1);
7    }
8  }

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

3.复制文件

 1 public void copyFile() throws IOException{
 2         FileInputStream iStream = new FileInputStream(new File("a.txt"));
 3         FileOutputStream oStream = new FileOutputStream(new File("acopy.txt"));
 4         byte [] bytes = new byte[2048];
 5         while(iStream.read(bytes) != -1){
 6             oStream.write(bytes);
 7         }
 8         oStream.flush();
 9         oStream.close();
10         iStream.close();
11     }

 

posted @ 2013-08-05 00:20  等风来。。  Views(328)  Comments(0Edit  收藏  举报
------------------------------------------------------------------------------------------------------------ --------------- 欢迎联系 x.guan.ling@gmail.com--------------- ------------------------------------------------------------------------------------------------------------