jar是一个单独的文件,里面的文件称之为资源,有两种方法获取,里面的资源文件。一般将资源文件放到resources文件夹中。
1. 推荐,静态和非静态方法中都能用 ClassName.class.getClassLoader().getResourceAsStream(path)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Tool {
public static void insertDataToDict(String path) throws IOException {
System.out.println("work dir:"+System.getProperty("user.dir"));
BufferedReader in = new BufferedReader(new InputStreamReader(Tool.class.getClassLoader().getResourceAsStream(path)));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
System.out.println("line: " + line);
buffer.append(line);
}
String input = buffer.toString();
}
}
2. 只有非静态方法中用 this.getClass().getClassLoader().getResourceAsStream(path)
public class Tool {
public void Tool() throws IOException {
String path = "userDict.txt";
BufferedReader in = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream(path)));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
System.out.println("line: " + line);
buffer.append(line);
}
}
}