轉自:http://lavasoft.blog.51cto.com/62575/265821/
├─src
│ └─com
│ └─lavasoft
│ ├─test
│ └─res
├─doc
import java.io.*;
/**
* Java讀取相對路徑的文件
*
* @author leizhimin 2010-1-15 10:59:43
*/
public class ReadFile {
public static void main(String[] args) {
readTextA_ByClassPath();
readTextA_ByProjectRelativePath();
readTextB_ByProjectRelativePath();
}
/**
* 通過工程相對路徑讀取(包內)文件,注意不以“/”開頭
*/
public static void readTextA_ByProjectRelativePath() {
System.out.println("-----------------readTextA_ByProjectRelativePath---------------------");
File f = new File("src/com/lavasoft/res/a.txt");
String a = file2String(f, "GBK");
System.out.println(a);
}
/**
* 通過工程相對路徑讀取(包外)文件,注意不以“/”開頭
*/
public static void readTextB_ByProjectRelativePath() {
System.out.println("-----------------readTextB_ByProjectRelativePath---------------------");
File f = new File("doc/b.txt");
String b = file2String(f, "GBK");
System.out.println(b);
}
/**
* 通過CLASSPATH讀取包內文件,注意以“/”開頭
*/
public static void readTextA_ByClassPath() {
System.out.println("-----------------readTextA_ByClassPath---------------------");
InputStream in = ReadFile.class.getResourceAsStream("/com/lavasoft/res/a.txt");
String a = stream2String(in, "GBK");
System.out.println(a);
}
/**
* 文件轉換爲字符串
*
* @param f 文件
* @param charset 文件的字符集
* @return 文件內容
*/
public static String file2String(File f, String charset) {
String result = null;
try {
result = stream2String(new FileInputStream(f), charset);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return result;
}
/**
* 文件轉換爲字符串
*
* @param in 字節流
* @param charset 文件的字符集
* @return 文件內容
*/
public static String stream2String(InputStream in, String charset) {
StringBuffer sb = new StringBuffer();
try {
Reader r = new InputStreamReader(in, charset);
int length = 0;
for (char[] c = new char[1024]; (length = r.read(c)) != -1;) {
sb.append(c, 0, length);
}
r.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
aaaaaaaaa
sssssssss
-----------------readTextA_ByProjectRelativePath---------------------
aaaaaaaaa
sssssssss
-----------------readTextB_ByProjectRelativePath---------------------
bbbbbbbbbbb
Process finished with exit code 0
import java.io.File;
/**
* CLASSPATH文件的絕對路徑獲取測試
*
* @author leizhimin 2010-1-18 9:33:02
*/
public class Test {
//classpath的文件路徑
private static String cp = "/com/lavasoft/cfg/syscfg.properties";
public static void main(String[] args) {
//當前類的絕對路徑
System.out.println(Test.class.getResource("/").getFile());
//指定CLASSPATH文件的絕對路徑
System.out.println(Test.class.getResource(cp).getFile());
//指定CLASSPATH文件的絕對路徑
File f = new File(Test.class.getResource(cp).getFile());
System.out.println(f.getPath());
}
}
/D:/projects/bbt/code/cdn/planrpt/out/production/planrpt/com/lavasoft/cfg/syscfg.properties
D:\projects\bbt\code\cdn\planrpt\out\production\planrpt\com\lavasoft\cfg\syscfg.properties
Process finished with exit code 0