JAR打包时的文件路径有关问题

JAR打包时的文件路径问题
在Java Project中运行调试时,对工程中的外部文件的访问没有任何问题,但是打包成jar后,发现原来的IO访问都提示找不到文件了,这个时候需要注意jar包中访问文件的路径问题,应该使用getResourceAsStream()方法来访问文件。

举例:
public class ReaderFile
{
    private static String txtFile = "test.txt";
    
    public static final String READ_FILE_ENCODING = "UTF-8";
    
    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);
        }
        reader.close();
        inStream.close();
        return (content.toString());
    }

    public static void main(String[] args) throws IOException
    {
        String content = readFileContent();
        System.out.println(content);
    }
}


此时的test.txt与ReaderFile.java在同一目录下,其他情况可自行修改路径