JAVA读取了本地TXT,但是导出JAR并运行时提示系统找不到指定路径求助

JAVA读取了本地TXT,但是导出JAR并运行时提示系统找不到指定路径求助,第1张

在编写代码时使用的是绝对路径来访问的这个文件,然而这个文件是在jar包中的,jar包中有自己的一套Url编址:jar:<url>!/{entry})。所以导致运行时无法访问到文件。

解决办法就是在构造File对象时使用url来构造,而文件的url获取使用ClassLoader

URL fileURL=thisgetClass()getResource("0txt");

File file = new File(fileURL);

FileInputStream fis = new FileInputStream(file);

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));

给你个例子,读取configproperties文件。

文件内容(值自己加)如下:

TestHosts =

FormalHosts =

TestConfig =

FormalConfig =

HostsPath =

ConfigPath =

读取文件的类如下:

import javaioBufferedInputStream;

import javaioFileInputStream;

import javaioFileNotFoundException;

import javaioIOException;

import javaioInputStream;

import javaioUnsupportedEncodingException;

import javautil;

public class EvnConfig{

public static Properties PROPERTIES = new Properties();

static{

String proFilePath = SystemgetProperty("userdir")+"/configproperties";

//Systemoutprintln(proFilePath);

//InputStream propertiesStream = EvnConfigclassgetClassLoader()getResourceAsStream(proFilePath);

InputStream in = null;

try {

in = new BufferedInputStream(new FileInputStream(proFilePath));

} catch (FileNotFoundException e1) {

// TODO Auto-generated catch block

e1printStackTrace();

}

try{

PROPERTIESload(in);

}catch(IOException e){

Systemoutprintln("properties创建失败!");

eprintStackTrace();

}

//Systemoutprintln("EvnConfigtestHosts:"+PROPERTIESgetProperty("TestHosts"));

}

public static final String testHosts = changeCode(PROPERTIESgetProperty("TestHosts"));

public static final String formalHosts = changeCode(PROPERTIESgetProperty("FormalHosts"));

public static final String testConfig = changeCode(PROPERTIESgetProperty("TestConfig"));

public static final String formalConfig = changeCode(PROPERTIESgetProperty("FormalConfig"));

public static final String hostsPath = changeCode(PROPERTIESgetProperty("HostsPath"));

public static final String configPath = changeCode(PROPERTIESgetProperty("ConfigPath"));

public static String changeCode(String str){

String toStr = "";

try {

//Systemoutprintln(str + "转换");

toStr = new String(strgetBytes("ISO-8859-1"),"GB2312");

//Systemoutprintln(str + "转换成功!");

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

Systemoutprintln(str + "转换失败!");

eprintStackTrace();

}

return toStr;

}

}

以上就是关于JAVA读取了本地TXT,但是导出JAR并运行时提示系统找不到指定路径求助全部的内容,包括:JAVA读取了本地TXT,但是导出JAR并运行时提示系统找不到指定路径求助、java 程序打包为jar发布后,读取配置文件路径出错 ,怎样获取配置文件路径、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/9612090.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-30
下一篇2023-04-30

发表评论

登录后才能评论

评论列表(0条)

    保存