Path and Resource in Java

zhaozj2021-02-16  57

I have been blurred on the path of Java, which is used to rarely. What you know is that if you use a relative path similar to "myfile.txt" or "res / image1.gif", it is a search under the root path. What is the root path? Feeling appears to be a path that contains an entry point (such as a main function). I know this is limited. Today, I have a problem, my program A needs to read a file from a sub-path, and the TestCase I have written "Root Path" is the path of Test Project, so that I can't guarantee reading. Take the correct file (for some reason, these files are static specified instead of running when running). In the Internet, there are two eyes. Try to pack it into JAR, it is useless (idiot, of course useless). Finally, I have found the answer in dear "Core Java Volume I". Excerpt reads as follows: 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 "So the foundation must be hit, the decision is still from the first chapter to start the old man to realize Core Java.

转载请注明原文地址:https://www.9cbs.com/read-18371.html

New Post(0)