Properties和IO流的读取路径

独孤帆 2010-06-07 04:23:20
我在SRC下建立了一个文件,用IO流读取的话路径是"src/xxxx.xx",用Properties只要"xxxx.xx"就能读取,为什么呢
...全文
167 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
dracularking 2010-06-08
  • 打赏
  • 举报
回复
补充下,是用的eclipse之类的吗?
IO的话应是以项目路径为默认根路径处理,所以加src,或者换bin试试?

Properties我不知道你怎么用的,但按照你的描述,应该是用了相对output folder的路径,即主要编译所产生class类的路径,另附:


// Load the user settings.
String userSettingsFile = System.getProperty("user.home")+"/user_settings.ini";
BufferedReader in = null;
try {
in = Utilities.getBufferedReader(userSettingsFile);
settings.load(in);
in.close();
} catch (Exception e) {
/* Program starts with default settings. */
}
finally {
if(in != null)
try {
in.close();
} catch (IOException e) {}
}



/**
* Returns a <code>BufferedReader</code> to the file corresponding to the passed filename.
* <p>
* This method searches for the file in the class path.
*
* @param filename the name of the file
* @return the <code>BufferedReader</code> to the file corresponding to the passed filename
*/
public static BufferedReader getBufferedReader(String filename) {

BufferedReader b = null;

// Try to read the file, no matter if it is in the class path or not.
try {
b = new BufferedReader(new FileReader(filename));
} catch (Exception e) {}

// If the program is started as web start application the file
// may be in the jar file.Hence try to read it from the jar, too.
try {
if(b == null)
b = new BufferedReader(new InputStreamReader(Main.class.getResourceAsStream(filename)));
} catch (Exception e) {}
return b;
}
  • 打赏
  • 举报
回复
这是相对路径,相对于这个路径 System.getProperty("user.dir");

不建议使用这样加载 .properties 文件,改为:

InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("xxx.properties");
properties.load(is);
Headsen 2010-06-07
  • 打赏
  • 举报
回复
classpath文件中找
如:

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="output" path="bin"/>
</classpath>
源路径默认src
若鱼1919 2010-06-07
  • 打赏
  • 举报
回复
IO流:使用文件相对路径
Properties:从classpath中查找

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧