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<list.size();i++){
if (i==0){
strBuffer.append(System.getProperty((String) list.get(0)));
}else{
strBuffer.append(File.separator+list.get(i));
}
}
}else{
for (int i=0;i<list.size();i++){
if (0 == path.indexOf("/")) //判斷path首字符有沒有"/"
strBuffer.append(File.separator+list.get(i));
else
strBuffer.append(list.get(i)+File.separator);
}
}
//3.處理路徑結尾的"/"問題
//->如果傳過來的路徑最后一個字符是"/",但是我們拼接的路徑最后一個字符不是"/"
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類針對是文件的本身,并不會操作文件的內容
*/