JAR包文件路径问题

问题描述:源码读取文件内容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,文件内容成功打印到控制台。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值