在程中我們常取一些資源的絕對徑,下面給出一個簡單方便的工具類來幫助我們輕松的找到我想的資源。(適用于CS/BS應用)
1
import java.io.File;
2
import java.io.IOException;
3
import java.net.URI;
4
import java.net.URISyntaxException;
5
6
/**
7
* @author <a href="mailto:maryang@live.cn">Maryang</a>
8
* @version $Revision: 1.0 $
9
* 這個類提供了一些根據類的class文件位置來定位的方法。
10
*/
11
public class PathUtil {
12
13
/**
14
* 獲取一個Class的絕對路徑
15
* @param clazz Class對象
16
* @return Class的絕對路徑
17
*/
18
public static String getPathByClass(Class clazz){
19
String path = null;
20
try {
21
URI uri = clazz.getResource("").toURI();
22
File file = new File(uri);
23
path = file.getCanonicalPath();
24
} catch (URISyntaxException e) {
25
e.printStackTrace();
26
} catch (IOException e) {
27
e.printStackTrace();
28
}
29
return path;
30
}
31
32
/**
33
* 獲取一個文件相對于一個Class相對的絕對路徑
34
* @param clazz Class對象
35
* @param relativePath Class對象的相對路徑
36
* @return 文件絕對路徑
37
*/
38
public static String getFilePathByClass(Class clazz,String relativePath){
39
String filePath = null;
40
String clazzPath = getPathByClass(clazz);
41
StringBuffer sbPath = new StringBuffer(clazzPath);
42
sbPath.append(File.separator);
43
sbPath.append(relativePath);
44
File file = new File(sbPath.toString());
45
try {
46
filePath = file.getCanonicalPath();
47
} catch (IOException e) {
48
e.printStackTrace();
49
}
50
return filePath;
51
}
52
53
public static void main(String[] args) {
54
try {
55
System.out.println(getPathByClass(PathUtil.class));
56
System.out.println(getFilePathByClass(PathUtil.class,"../../images/logo.gif"));
57
} catch (Exception e) {
58
e.printStackTrace();
59
}
60
}
61
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

杰森
郵箱:json.shen(at)gmail.com
網站:www.shenjia.org