Java中的路径及Resource介绍

Java中的路径及Resource介绍

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

在网上四处乱撞,两眼一抹黑。试着打包成jar,也没用(笨蛋,当然没用)。最后还是在亲爱的《CoreJavaVolumeI》中找到了答案。摘抄原文如下:
Theresourcemechanismgivesyouthesameconvenienceforfilesthataren''tclassfiles.Herearethenecessarysteps:
GettheClassobjectoftheclassthathasaresource,forexample,AboutPanel.class.
CallgetResource(filename)togettheresourcelocationasaURL.
Iftheresourceisanimageoraudiofile,readitdirectlywiththegetImageorgetAudioClipmethod.
Otherwise,usetheopenStreammethodontheURLtoreadinthedatainthefile.(SeeChapter12formoreonstreams.)
Thepointisthattheclassloaderremembershowtolocatetheclass,andthenitcansearchfortheassociatedresourceinthesamelocation.
Forexample,tomakeaniconwiththeimagefileabout.gif,dothefollowing:

URLurl=AboutPanel.class.getResource("about.gif");
ImageIconicon=newImageIcon(url);
Thatmeans"locatetheabout.giffileatthesameplacewhereyoufindAboutPanel.class."

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