zoukankan      html  css  js  c++  java
  • 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 名称可以包括共享名称下的目录路径,格式为: \servernamesharenamedirectoryfilename。

    一个在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:Tempdocumentation.newREADME"则会返回"newREADME"。但这不是我们想要的结果。

    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     }
  • 相关阅读:
    0523注册审核
    0520三级联动
    0519考试练习题
    0516ajax
    mysql 高级查询
    mysql
    HTML的格局与布局
    css样式表
    HTML表单
    HTML
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3237345.html
Copyright © 2011-2022 走看看