问题描述:源码读取文件内容OK,但是打成jar包后,导入到另外一个工程中后,读取文件内容出错,java.io.FileNotFoundException:找不到文件?!
解决方案:读取jar包中文件内容,必须采用getResourceAsStream("path")的方式来获取(该 文件必须在src目录或其子目录下才能获取到 )。
===================================================
1、在src目录下创建一个test.txt,并写入一些数据;
2、编写读取文件数据类 ;
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ReaderFile
{
private static String txtFile = "test.txt";
public static final String READ_FILE_ENCODING = "UTF-8";
public static final String NEW_LINE = System.getProperty("line.separator");
public static String readFileContent() throws IOException
{
InputStream inStream = ReaderFile.class.getResourceAsStream("/" + txtFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, READ_FILE_ENCODING));
StringBuilder content = new StringBuilder();
String line = null;
while (null != (line = reader.readLine()))
{
content.append(line);
content.append(NEW_LINE);
}
reader.close();
inStream.close();
return (content.toString());
}
public static void main(String[] args) throws IOException
{
// System.getProperties().list(System.out);
String content = readFileContent();
System.out.println(content);
}
}
3、将读取文件内容打成readfile.jar
4、在另外一个工程中引入该jar包,调用读取文件内容方法:
package readfiletest;
import java.io.IOException;
import test.ReaderFile;
public class TestReadFile
{
public static void main(String[] args) throws IOException
{
String content = ReaderFile.readFileContent();
System.out.println(content);
}
}
5、测试OK,文件内容成功打印到控制台。