Java中的路径及Resource

     一直对Java的路径感觉模糊,用起来稀里糊涂。所知道的就是,如果使用相对路径类似于"myfile.txt"或者"res/image1.gif"的话,是在根路径下进行搜索的。
    而根路径到底是什么?感觉上似乎是包含了入口点(例如main函数)的类所在的路径。所知仅限于此。
    今天碰到一个问题,我的程序A需要从它的某个子路径读取一个文件,而我所编写的TestCase在运行时“根路径”就是Test Project的路径,这样一来,怎么也不能保证读取到正确的文件(由于某些原因,这些文件是静态指定的,而不是运行时动态传入的)。

    在网上四处乱撞,两眼一抹黑。试着打包成jar,也没用(笨蛋,当然没用)。最后还是在亲爱的《Core Java Volume I》中找到了答案。摘抄原文如下:
    The resource mechanism gives you the same convenience for files that aren''t class files. Here are the necessary steps:
 Get the Class object of the class that has a resource, for example, AboutPanel.class.
 Call getResource(filename) to get the resource location as a URL.
    If the resource is an image or audio file, read it directly with the getImage or getAudioClip method.
 Otherwise, use the openStream method on the URL to read in the data in the file. (See Chapter 12 for more on streams.)
 The point is that the class loader remembers how to locate the class, and then it can search for the associated resource in the same location.
 For example, to make an icon with the image file about.gif, do the following:

    URL url = AboutPanel.class.getResource("about.gif");
    ImageIcon icon = new ImageIcon(url);
 That means "locate the about.gif file at the same place where you find AboutPanel.class."

 所以说基础一定要打好,决定还是从第一章开始老老实实啃Core Java吧。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值