File类的使用

JQPathTool工具类:用来处理路径

package File;
import java.io.*;
import java.util.*;

public class JQPathTool {
    
    public static final String Desktop = getPath("user.home/Desktop");
    public static final String Home = System.getProperty("user.home");
    
    public static String getPath(String path){
        StringBuffer strBuffer = new StringBuffer();
        //0.用"/"来分割字符串path
        List list = new ArrayList(Arrays.asList(path.split("/"))); //只有new的才能产生自己的内存,才能实现增删操作
        //        if(list.contains("")) list.remove("");
        Iterator it =  list.iterator();
        while(it.hasNext()){
            String s = (String)it.next();
            if (s.equals(""))
                it.remove();
        }
        /*
         /a/b/这样拆分会出现""空对象
         所以要把这个空对象删除掉,所以转成list操作
         一种是判断是否包含,然后删除;
         一种是遍历然后删除,在有多个""对象的情况下考虑遍历;
         保险起见,用遍历吧
         */
        
        //1.如果没有分隔符,那么直接返回输入的路径
        if (-1 == path.indexOf("/")) return path;
        
        //2.判断路径中是否包含系统目录
        if (-1 != ((String) list.get(0)).indexOf("user.")){ //如果arr[0]中包含"user."字样就代表有系统目录标识
            for (int i=0;i如果传过来的路径最后一个字符是"/",但是我们拼接的路径最后一个字符不是"/"
        if (path.substring(path.length()-1).equals("/") && !strBuffer.substring(path.length()-1).equals("/")){
            strBuffer.append(File.separator);
        }
        //->如果传过来的路径最后一个字符不是"/",但是我们拼接的路径最后一个字符是"/"
        if (!path.substring(path.length()-1).equals("/") && strBuffer.substring(path.length()-1).equals("/")){
            strBuffer.deleteCharAt(strBuffer.length()-1);
        }
        
        return strBuffer.toString();
    }
}
/*
 System.getProperty(String)通过制定的key获取系统目录
 */

Test

package File;

import java.io.File;

public class Test {
    
    public static void main(String[] args) {
        String path = JQPathTool.getPath("user.home/Desktop/Test.txt");
        File f = new File(path);
        if (f.exists()){
            f.delete();
        }else{
            try{
                f.createNewFile();
            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
    }
}

/*
 File类针对是文件的本身,并不会操作文件的内容
 */

你可能感兴趣的:(File类的使用)