# Resources (on classpath)
Java allows the retrieval of file-based resources stored inside of a JAR alongside compiled classes. This topic focuses on loading those resources and making them available to your code.
# Loading default configuration
To read default configuration properties:
# Loading an image from a resource
To load a bundled image:
# Finding and reading resources using a classloader
Resource loading in Java comprises the following steps:
- Finding the Class or ClassLoader that will find the resource.
- Finding the resource.
- Obtaining the byte stream for the resource.
- Reading and processing the byte stream.
- Closing the byte stream.
The last three steps are typically accomplished by passing the URL to a library method or constructor to load the resource. You will typically use a getResource method in this case. It is also possible to read the resource data in application code. You will typically use getResourceAsStream in this case.
# Absolute and relative resource paths
Resources that can be loaded from the classpath are denoted by a path. The syntax of the path is similar to a UNIX / Linux file path. It consists of simple names separated by forward slash ( / ) characters. A relative path starts with a name, and an absolute path starts with a separator.
As the Classpath examples describe, a JVM’s classpath defines a namespace by overlaying the namespaces of the directories and JAR or ZIP files in the classpath. When an absolute path is resolved, it the classloaders interpret the initial / as meaning the root of the namespace. By contrast, a relative path may be resolved relative to any "folder" in the namespace. The folder used will depend on the object that you use to resolve the path.
# Obtaining a Class or Classloader
A resource can be located using either a Class object or a ClassLoader object. A Class object can resolve relative paths, so you will typically use one of these if you have a (class) relative resource. There are a variety of ways to obtain a Class object. For example:
A ClassLoader object is typically obtained by calling getClassLoader() on a Class object. It is also possible to get hold of the JVM’s default classloader using the static ClassLoader.getSystemClassLoader() method.
# The get methods
Once you have a Class or ClassLoader instance, you can find a resource, using one of the following methods:
Methods | Description |
---|---|
ClassLoader.getResource(path) ClassLoader.getResources(path) |
Returns a URL which represents the location of the resource with the given path. |
ClassLoader.getResources(path) Class.getResources(path) |
Returns an Enumeration<URL> giving the URLs which can be used to locate the foo.bar resource; see below. |
ClassLoader.getResourceAsStream(path) Class.getResourceStream(path) |
Returns an InputStream from which you can read the contents of the foo.bar resource as a sequence of bytes. |
-
— The `Class` methods resolve a relative path in the "folder" that corresponds to the classes package. — The `ClassLoader` methods treat relative paths as if they were absolute; i.e. the resolve them in the "root folder" of the classpath namespace.
If the requested resource (or resources) cannot be found, the getResource and getResourceAsStream methods return null , and the getResources methods return an empty Enumeration`.
The URLs returned will be resolvable using URL.toStream() . They could be file: URLs or other conventional URLs, but if the resource resides in a JAR file, they will be jar: URLs that identify the JAR file and a specific resource within it.
If your code uses a getResourceAsStream method (or URL.toStream() ) to obtain an InputStream , it is responsible for closing the stream object. Failure to close the stream could lead to a resource leak.
# Loading same-name resource from multiple JARs
Resource with same path and name may exist in more than one JAR file on the classpath. Common cases are resources following a convention or that are part of a packaging specification. Examples for such resources are
- META-INF/MANIFEST.MF
- META-INF/beans.xml (CDI Spec)
- ServiceLoader properties containing implementation providers
To get access to all of these resources in different jars, one has to use a ClassLoader, which has a method for this. The returned Enumeration can be conveniently converted to a List using a Collections function.
# Remarks
A resource is file-like data with a path-like name, which resides in the classpath. The most common use of resources is bundling application images, sounds, and read-only data (such as default configuration).
Resources can be accessed with the ClassLoader.getResource
(opens new window) methods. The most common use case is to have resources placed in the same package as the class which reads them; the Class.getResource
(opens new window) methods serve this common use case.
The only difference between a getResource method and getResourceAsStream method is that the former returns a URL, while the latter opens that URL and returns an InputStream.
The methods of ClassLoader accept a path-like resource name as an argument and search each location in the ClassLoader’s classpath for an entry matching that name.
- If a classpath location is a .jar file, a jar entry with the specified name is considered a match.
- If a classpath location is a directory, a relative file under that directory with the specified name is considered a match.
The resource name is similar to the path portion of a relative URL. On all platforms, it uses forward slashes ( / ) as directory separators. It must not start with a slash.
The corresponding methods of Class are similar, except:
- The resource name may start with a slash, in which case that initial slash is removed and the rest of the name is passed to the corresponding method of ClassLoader.
- If the resource name does not start with a slash, it is treated as relative to the class whose getResource or getResourceAsStream method is being called. The actual resource name becomes package/name, where package is the name of the package to which the class belongs, with each period replaced by a slash, and name is the original argument given to the method.
Resources should be placed in named packages, rather than in the root of a .jar file, for the same reason classes are placed in packages: To prevent collisions among multiple vendors. For example, if multiple .jar files are in the classpath, and more than one of them contains a config.properties entry in its root, calls to the getResource or getResourceAsStream methods will return the config.properties from whichever .jar is listed first in the classpath. This is not predictable behavior in environments where the classpath order is not under the direct control of the application, such as Java EE.
All getResource and getResourceAsStream methods return null if the specified resource does not exist. Since resources must be added to the application at build time, their locations should be known when the code is being written; a failure to find a resource at runtime is usually the result of programmer error.
Resources are read-only. There is no way to write to a resource. Novice developers often make the mistake of assuming that since the resource is a separate physical file when developing in an IDE (like Eclipse), it will be safe to treat it like a separate physical file in the general case. However, this is not correct; applications are almost always distributed as archives such as .jar or .war files, and in such cases, a resource will not be a separate file and will not be writable. (The getFile method of the URL class is not a workaround for this; despite its name, it merely returns the path portion of a URL, which is by no means guaranteed to be a valid filename.)
There is no safe way to list resources at runtime. Again, since the developers are responsible for adding resource files to the application at build time, developers should already know their paths. While there are workarounds, they are not reliable and will eventually fail.
Загрузка файла из ресурсной папки в Java
Во время работы с Java-проектами, особенно с Maven, часто возникает необходимость загрузить файл, расположенный в ресурсной папки. Например, это может быть файл с настройками, образцы данных для тестирования или что-нибудь ещё.
Структура проекта может выглядеть примерно так:
Если в папке /src/test/resources/ есть файл test.csv , который необходимо загрузить во время выполнения теста, расположенного в /src/test/java/MyTest.java , возникает вопрос: как это сделать правильно?
Неправильные подходы
Одна из распространённых ошибок — попытка загрузить файл напрямую, как обычно:
Этот подход не сработает, так как путь до файла указан неправильно. Java попытается найти файл в корневой директории проекта, а не в папке ресурсов.
Другой неработающий подход — попытаться загрузить ресурс через класс:
В этом случае Java попытается найти файл в той же пакетной структуре, что и класс MyTest, что тоже не является правильным путём до файла.
Правильный подход
Чтобы загрузить файл из ресурсной папки, нужно использовать метод Class#getResourceAsStream(String) , указав путь до файла относительно ресурсной папки:
В этом случае / в начале пути говорит Java о том, что нужно искать файл относительно корневой папки ресурсов, а не относительно структуры пакетов.
Итак, подведём итог: для загрузки файлов из ресурсной папки в Java нужно использовать метод getResourceAsStream(String) , указывая путь до файла относительно корневой папки ресурсов.
Java как указать путь к файлу из resources
В этой статье будет показано, как прочитать файл из папки “ресурсы”, “getResourceAsStream” или “getResource”.
- Автор записи
Автор оригинала: mkyong.
В Java мы можем использовать getResourceAsStream или getResource для чтения файла или нескольких файлов из папки ресурсы или корневого каталога пути к классу.
Метод getResourceAsStream возвращает Входной поток .
Метод getResource возвращает URL и обычно преобразует его в Файл ; Не работает в файле JAR .
1. Файлы в ресурсах папка
1.1 Просмотрите файлы в src/main/ресурсы , позже мы получим доступ к файлам и распечатаем содержимое файла.
1.2 По умолчанию инструменты сборки, такие как Maven, Gradle или обычная практика Java, будут копировать все файлы из src/основные/ресурсы в корневой каталог целевые/классы или сборка/классы . Итак, когда мы пытаемся прочитать файл из src/main/ресурсы , мы читаем файл из корневого каталога пути к классам проекта.
1.3 Ниже приведена структура файла JAR. Обычно файлы в папке ресурсы копируются в корневой каталог пути к классу.
2. Получите файл из папки ресурсов.
2.1 Приведенный ниже пример демонстрирует использование getResourceAsStream и getResource методы чтения файла json/файл 1.json из папки ресурсы
- Метод getResource не работает в файле JAR.
- Метод getResourceAsStream работает везде.
2.2 Теперь мы упаковываем проект в файл JAR и запускаем его; на этот раз getResource завершится ошибкой и вернет либо Исключение NoSuchFileException , либо Исключение InvalidPathException . Мы не можем прочитать файлы внутри файла JAR по URL-адресу ресурса.
Запустите файл JAR в Linux (Ubuntu), он вызовет Исключение NoSuchFileException .
Запустите файл JAR в Windows, он вызовет Исключение InvalidPathException .
P.S В этом примере используется плагин Maven maven-jar-плагин чтобы создать файл JAR.
3. Получите файл из папки ресурсов – Модульный тест
3.1 Мы помещаем тестовые ресурсы в папку src/test/ресурсы для модульных тестов. Обычно файлы в тестовых ресурсах копируются в папку target/test-classes .
3.2 Это работает так же, как мы читаем файл из src/main/ресурсы . Мы используем то же самое getResourceAsStream и getResource методы чтения файла из src/test/ресурсов .
4. Получите все файлы из папки ресурсов. (Среда, ОТЛИЧНАЯ от JAR)
Если мы не знаем точного имени файла и хотим прочитать все файлы, включая файлы вложенных папок из папки ресурсов, мы можем использовать NIO Файлы.перейдите , чтобы легко получить доступ к файлам и прочитать их.
4.1 В приведенном ниже примере используются Файлы.пройдите чтобы прочитать все файлы из папки src/основные/ресурсы/json :
4.2 Однако стандартные Файлы.прогулка в примере 4.1 не удается получить доступ к файлам в файле JAR напрямую, попробуйте запустить пример 4.1 в среде JAR, и он выдает Исключение FileSystemNotFoundException .
Java-путь к файлу в src / main / resources
У меня есть модуль maven со следующей структурой каталогов, и я хочу получить путь к abc.access в abcManager.java.
Я попробовал это с помощью abcManager.class.getResource(«abc.access») , но это дает ноль.
Я прошел ниже вопросы, но решения не сработали.
5 ответов
Проблема была в том, что я не включил ресурс в сборку maven в pom-файле. Когда я добавил следующее, он работал с abcManager.class.getResource(«/abc.access»)
Class.getResource является локальным для класса, в данном случае это пакет org.abc.xyz.init. Вы пытаетесь прочитать src / main / resources / org / ABC / xyz / init / abc.access. В качестве альтернативы загрузчику классов, который всегда загружается из корня пути к классам, вы также можете сделать class.getResource («/ abc.access»)
Следующее должно работать.
При условии, что вы работаете внутри IDE (например, Eclipse). Если вы пытаетесь сделать это из командной строки, вам нужно явно установить classpath.
Location-Independent Access to Resources
A resource is data (images, audio, text, and so on) that a program needs to access in a way that is independent of the location of the program code. Java programs can use two mechanisms to access resources: Applets use Applet.getCodeBase() to get the base URL for the applet code and then extend the base URL with a relative path to load the desired resource, for example with Applet.getAudioClip(url) . Applications use «well known locations» such as System.getProperty(«user.home») or System.getProperty(«java.home») , then add «/lib/resource«, and open that file.
Methods in the classes Class and ClassLoader provide a location-independent way to locate resources. For example, they enable locating resources for:
- An applet loaded from the Internet using multiple HTTP connections.
- An applet loaded using JAR files.
- A Java Bean loaded or installed in the CLASSPATH.
- A «library» installed in the CLASSPATH.
These methods do not provide specific support for locating localized resources. Localized resources are supported by the internationalization facilities.
Resources, names, and contexts
A resource is identified by a string consisting of a sequence of substrings, delimited by slashes (/), followed by a resource name. Each substring must be a valid Java identifier. The resource name is of the form shortName or shortName.extension . Both shortName and extension must be Java identifiers.
The name of a resource is independent of the Java implementation; in particular, the path separator is always a slash (/). However, the Java implementation controls the details of how the contents of the resource are mapped into a file, database, or other object containing the actual resource.
The interpretation of a resource name is relative to a class loader instance. Methods implemented by the ClassLoader class do this interpretation.
System Resources
A system resource is a resource that is either built-in to the system, or kept by the host implementation in, for example, a local file system. Programs access system resources through the ClassLoader methods getSystemResource and getSystemResourceAsStream .
For example, in a particular implementation, locating a system resource may involve searching the entries in the CLASSPATH. The ClassLoader methods search each directory, ZIP file, or JAR file entry in the CLASSPATH for the resource file, and, if found, returns either an InputStream , or the resource name. If not found, the methods return null. A resource may be found in a different entry in the CLASSPATH than the location where the class file was loaded.
Non-System Resources
The implementation of getResource on a class loader depends on the details of the ClassLoader class. For example, AppletClassLoader :
- First tries to locate the resource as a system resource; then, if not found,
- Searches through the resources in archives (JAR files) already loaded in this CODEBASE; then, if not found,
- Uses CODEBASE and attempts to locate the resource (which may involve contacting a remote site).
All class loaders will search for a resource first as a system resource, in a manner analogous to searcing for class files. This search rule permits overwriting locally any resource. Clients should choose a resource name that will be unique (using the company or package name as a prefix, for instance).
Resource Names
A common convention for the name of a resource used by a class is to use the fully qualified name of the package of the class, but convert all periods (.) to slashes (/), and add a resource name of the form name.extension . To support this, and to simplify handling the details of system classes (for which getClassLoader returns null), the class Class provides two convenience methods that call the appropriate methods in ClassLoader .
The resource name given to a Class method may have an initial starting «/» that identifies it as an «absolute» name. Resource names that do not start with a «/» are «relative».
Absolute names are stripped of their starting «/» and are passed, without any further modification, to the appropriate ClassLoader method to locate the resource. Relative names are modified according to the convention described previously and then are passed to a ClassLoader method.
Using Methods of java.lang.Class
The Class class implements several methods for loading resources.
The method getResource() returns a URL for the resource. The URL (and its representation) is specific to the implementation and the JVM (that is, the URL obtained in one runtime instance may not work in another). Its protocol is usually specific to the ClassLoader loading the resource. If the resource does not exist or is not visible due to security considerations, the methods return null.
If the client code wants to read the contents of the resource as an InputStream , it can apply the openStream() method on the URL. This is common enough to justify adding getResourceAsStream() to Class and ClassLoader . getResourceAsStream() the same as calling getResource().openStream() , except that getResourceAsStream() catches IO exceptions returns a null InputStream .
Client code can also request the contents of the resource as an object by applying the java.net.URL.getContent() method on the URL. This is useful when the resource contains the data for an image, for instance. In the case of an image, the result is an awt.image.ImageProducer object, not an Image object.
The getResource and getResourceAsStream methods find a resource with a given name. They return null if they do not find a resource with the specified name. The rules for searching for resources associated with a given class are implemented by the class’s ClassLoader. The Class methods delegate to ClassLoader methods, after applying a naming convention: if the resource name starts with «/», it is used as is. Otherwise, the name of the package is prepended, after converting all periods (.) to slashes (/).
The resolveName method adds a package name prefix if the name is not absolute, and removes any leading «/» if the name is absolute. It is possible, though uncommon, to have classes in diffent packages sharing the same resource.
Using Methods of java.lang.ClassLoader
The ClassLoader class has two sets of methods to access resources. One set returns an InputStream for the resource. The other set returns a URL. The methods that return an InputStream are easier to use and will satisfy many needs, while the methods that return URLs provide access to more complex information, such as an Image and an AudioClip.
The ClassLoader manges resources similarly to the way it manages classes. A ClassLoader controls how to map the name of a resource to its content. ClassLoader also provides methods for accessing system resources, analogous to the system classes. The Class class provides some convenience methods that delegate functionality to the ClassLoader methods.
Many Java programs will access these methods indirectly through the I18N (localization) APIs. Others will access it through methods in Class . A few will directly invoke the ClassLoader methods.
The methods in ClassLoader use the given String as the name of the resource without applying any absolute/relative transformation (see the methods in Class). The name should not have a leading «/».
System resources are those that are handled by the host implemenation directly. For example, they may be located in the CLASSPATH.
The name of a resource is a «/»-separated sequence of identifiers. The Class class provides convenience methods for accessing resources; the methods implement a convention where the package name is prefixed to the short name of the resource.
Resources can be accessed as an InputStream , or a URL.
The getSystemResourceAsStream method returns an InputStream for the specified system resource or null if it does not find the resource. The resource name may be any system resource.
The getSystemResource method finds a system resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java.net.URL.getContent() with the URL will return an object such as ImageProducer , AudioClip , or InputStream .
The getResourceAsStream method returns an InputStream for the specified resource or null if it does not find the resource.
The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java.net.URL.getContent() with the URL will return an object such as ImageProducer , AudioClip , or InputStream .
Security
Since getResource() provides access to information, it must have well-defined and well-founded security rules. If security considerations do not allow a resource to be visible in some security context, the getResource() method will fail (return null) as if the resource were not present at all, this addresses existence attacks.
ClassLoader.getResource and ClassLoader.getSystemResource() and extend to the AsStream methods as defined in the previous section. —>
Class loaders may not provide access to the contents of a .class file for both security and performance reasons. Whether it is possible to obtain a URL for a .class file depends on the specifics, as shown below.
There are no specified security issues or restrictions regarding resources that are found by a non-system class loader. AppletClassLoader provides access to information that is loaded from a source location, either individually, or in a group through a JAR file; thus AppletClassLoader should apply the same checkConnect() rules when dealing with URLs through getResource() .
The system ClassLoader provides access to information in the CLASSPATH. A CLASSPATH may contain directories and JAR files. Since a JAR file is created intentionally, it has a different significance than a directory where things may end up in a more casual manner. In particular, we are more strict on getting information out of a directory than out from a JAR file.
If a resource is in a directory:
- getResource() invocations will use File.exists() to determine whether to make the corresponding file visible to the user. Recall that File.exists() uses the checkRead() method in the security manager.
- the same applies to getResourceAsStream() .
If the resource is in a JAR file:
- getResource() invocations will succeed for all files, regardless of whether the invocation is done from within a system or a non-system class.
- getResourceAsStream() invocations will succeed for non .class resources, and so will for java.net.URL.getContent() on corresponding URLs.
Examples
This section provides two examples of client code. The first example uses «absolute resource» names and traditional mechanisms to get a Class object.
This example uses «relative resource» names and the mechanism available from the compiler through the -experimental flag, to get a Class object.
How to Read a File from Resources Folder in Java
When you build a java project and pack it into a jar (or a war), the files under the resources folder are included into the jar. These files may include configuration files, scripts and other resources needed during run time. When the software is executed, it may need to load the contents of these files for some kind of processing — may be properties, sql statements, etc. In this article, we show you how to load these resources when the program is running.
2. Packaging Resources
Check out the directory hierarchy below:
Maven packs all the files and folders under main/resources into the jar file at the the root. You can access these files and folders from your java code as shown below.
3. Loading the Resources
The following code snippet shows how to load resources packed thus into the jar or war file:
Using the method Class.getResourceAsStream(String), you can get an InputStream to read the resource. The method returns null if the resource cannot be found or loaded.
To read binary resources, you can use directly use the InputStream instance. For reading a text resource, you can convert it to a Reader instance, possibly specifying the character encoding:
4. Using Absolute Path of Resource
To load a resource whose full path from the root of the jar file is known, use the full path starting with a “ / “.
Как получить абсолютный путь к файлу в папке / resources в вашем проекте
В Java, как я могу получить абсолютный путь к файлу, пожалуйста?
4 ответа
Вы можете создать объект File и использовать метод getAbsolutePath :
Правильный способ работы:
Теперь не имеет значения, где физически находится файл в пути к классам, он будет найден до тех пор, пока ресурс фактически является файлом, а не записью JAR.
(Казалось, очевидный new File(resource.getPath()) не работает для всех путей! Путь по-прежнему кодируется URL-адресом!)
создать класс classLoader, тогда вы можете легко получить доступ к файлам или ресурсам. теперь вы получаете доступ к пути, используя метод getPath() этого класса.
Java как указать путь к файлу из resources
В этой статье будет показано, как прочитать файл из папки “ресурсы”, “getResourceAsStream” или “getResource”.
- Автор записи
Автор оригинала: mkyong.
В Java мы можем использовать getResourceAsStream или getResource для чтения файла или нескольких файлов из папки ресурсы или корневого каталога пути к классу.
Метод getResourceAsStream возвращает Входной поток .
Метод getResource возвращает URL и обычно преобразует его в Файл ; Не работает в файле JAR .
1. Файлы в ресурсах папка
1.1 Просмотрите файлы в src/main/ресурсы , позже мы получим доступ к файлам и распечатаем содержимое файла.
1.2 По умолчанию инструменты сборки, такие как Maven, Gradle или обычная практика Java, будут копировать все файлы из src/основные/ресурсы в корневой каталог целевые/классы или сборка/классы . Итак, когда мы пытаемся прочитать файл из src/main/ресурсы , мы читаем файл из корневого каталога пути к классам проекта.
1.3 Ниже приведена структура файла JAR. Обычно файлы в папке ресурсы копируются в корневой каталог пути к классу.
2. Получите файл из папки ресурсов.
2.1 Приведенный ниже пример демонстрирует использование getResourceAsStream и getResource методы чтения файла json/файл 1.json из папки ресурсы
- Метод getResource не работает в файле JAR.
- Метод getResourceAsStream работает везде.
2.2 Теперь мы упаковываем проект в файл JAR и запускаем его; на этот раз getResource завершится ошибкой и вернет либо Исключение NoSuchFileException , либо Исключение InvalidPathException . Мы не можем прочитать файлы внутри файла JAR по URL-адресу ресурса.
Запустите файл JAR в Linux (Ubuntu), он вызовет Исключение NoSuchFileException .
Запустите файл JAR в Windows, он вызовет Исключение InvalidPathException .
P.S В этом примере используется плагин Maven maven-jar-плагин чтобы создать файл JAR.
3. Получите файл из папки ресурсов – Модульный тест
3.1 Мы помещаем тестовые ресурсы в папку src/test/ресурсы для модульных тестов. Обычно файлы в тестовых ресурсах копируются в папку target/test-classes .
3.2 Это работает так же, как мы читаем файл из src/main/ресурсы . Мы используем то же самое getResourceAsStream и getResource методы чтения файла из src/test/ресурсов .
4. Получите все файлы из папки ресурсов. (Среда, ОТЛИЧНАЯ от JAR)
Если мы не знаем точного имени файла и хотим прочитать все файлы, включая файлы вложенных папок из папки ресурсов, мы можем использовать NIO Файлы.перейдите , чтобы легко получить доступ к файлам и прочитать их.
4.1 В приведенном ниже примере используются Файлы.пройдите чтобы прочитать все файлы из папки src/основные/ресурсы/json :
4.2 Однако стандартные Файлы.прогулка в примере 4.1 не удается получить доступ к файлам в файле JAR напрямую, попробуйте запустить пример 4.1 в среде JAR, и он выдает Исключение FileSystemNotFoundException .
Java-путь к файлу в src / main / resources
У меня есть модуль maven со следующей структурой каталогов, и я хочу получить путь к abc.access в abcManager.java.
Я попробовал это с помощью abcManager.class.getResource(«abc.access») , но это дает ноль.
Я прошел ниже вопросы, но решения не сработали.
5 ответов
Проблема была в том, что я не включил ресурс в сборку maven в pom-файле. Когда я добавил следующее, он работал с abcManager.class.getResource(«/abc.access»)
Class.getResource является локальным для класса, в данном случае это пакет org.abc.xyz.init. Вы пытаетесь прочитать src / main / resources / org / ABC / xyz / init / abc.access. В качестве альтернативы загрузчику классов, который всегда загружается из корня пути к классам, вы также можете сделать class.getResource («/ abc.access»)
Следующее должно работать.
При условии, что вы работаете внутри IDE (например, Eclipse). Если вы пытаетесь сделать это из командной строки, вам нужно явно установить classpath.
Location-Independent Access to Resources
A resource is data (images, audio, text, and so on) that a program needs to access in a way that is independent of the location of the program code. Java programs can use two mechanisms to access resources: Applets use Applet.getCodeBase() to get the base URL for the applet code and then extend the base URL with a relative path to load the desired resource, for example with Applet.getAudioClip(url) . Applications use «well known locations» such as System.getProperty(«user.home») or System.getProperty(«java.home») , then add «/lib/resource«, and open that file.
Methods in the classes Class and ClassLoader provide a location-independent way to locate resources. For example, they enable locating resources for:
- An applet loaded from the Internet using multiple HTTP connections.
- An applet loaded using JAR files.
- A Java Bean loaded or installed in the CLASSPATH.
- A «library» installed in the CLASSPATH.
These methods do not provide specific support for locating localized resources. Localized resources are supported by the internationalization facilities.
Resources, names, and contexts
A resource is identified by a string consisting of a sequence of substrings, delimited by slashes (/), followed by a resource name. Each substring must be a valid Java identifier. The resource name is of the form shortName or shortName.extension . Both shortName and extension must be Java identifiers.
The name of a resource is independent of the Java implementation; in particular, the path separator is always a slash (/). However, the Java implementation controls the details of how the contents of the resource are mapped into a file, database, or other object containing the actual resource.
The interpretation of a resource name is relative to a class loader instance. Methods implemented by the ClassLoader class do this interpretation.
System Resources
A system resource is a resource that is either built-in to the system, or kept by the host implementation in, for example, a local file system. Programs access system resources through the ClassLoader methods getSystemResource and getSystemResourceAsStream .
For example, in a particular implementation, locating a system resource may involve searching the entries in the CLASSPATH. The ClassLoader methods search each directory, ZIP file, or JAR file entry in the CLASSPATH for the resource file, and, if found, returns either an InputStream , or the resource name. If not found, the methods return null. A resource may be found in a different entry in the CLASSPATH than the location where the class file was loaded.
Non-System Resources
The implementation of getResource on a class loader depends on the details of the ClassLoader class. For example, AppletClassLoader :
- First tries to locate the resource as a system resource; then, if not found,
- Searches through the resources in archives (JAR files) already loaded in this CODEBASE; then, if not found,
- Uses CODEBASE and attempts to locate the resource (which may involve contacting a remote site).
All class loaders will search for a resource first as a system resource, in a manner analogous to searcing for class files. This search rule permits overwriting locally any resource. Clients should choose a resource name that will be unique (using the company or package name as a prefix, for instance).
Resource Names
A common convention for the name of a resource used by a class is to use the fully qualified name of the package of the class, but convert all periods (.) to slashes (/), and add a resource name of the form name.extension . To support this, and to simplify handling the details of system classes (for which getClassLoader returns null), the class Class provides two convenience methods that call the appropriate methods in ClassLoader .
The resource name given to a Class method may have an initial starting «/» that identifies it as an «absolute» name. Resource names that do not start with a «/» are «relative».
Absolute names are stripped of their starting «/» and are passed, without any further modification, to the appropriate ClassLoader method to locate the resource. Relative names are modified according to the convention described previously and then are passed to a ClassLoader method.
Using Methods of java.lang.Class
The Class class implements several methods for loading resources.
The method getResource() returns a URL for the resource. The URL (and its representation) is specific to the implementation and the JVM (that is, the URL obtained in one runtime instance may not work in another). Its protocol is usually specific to the ClassLoader loading the resource. If the resource does not exist or is not visible due to security considerations, the methods return null.
If the client code wants to read the contents of the resource as an InputStream , it can apply the openStream() method on the URL. This is common enough to justify adding getResourceAsStream() to Class and ClassLoader . getResourceAsStream() the same as calling getResource().openStream() , except that getResourceAsStream() catches IO exceptions returns a null InputStream .
Client code can also request the contents of the resource as an object by applying the java.net.URL.getContent() method on the URL. This is useful when the resource contains the data for an image, for instance. In the case of an image, the result is an awt.image.ImageProducer object, not an Image object.
The getResource and getResourceAsStream methods find a resource with a given name. They return null if they do not find a resource with the specified name. The rules for searching for resources associated with a given class are implemented by the class’s ClassLoader. The Class methods delegate to ClassLoader methods, after applying a naming convention: if the resource name starts with «/», it is used as is. Otherwise, the name of the package is prepended, after converting all periods (.) to slashes (/).
The resolveName method adds a package name prefix if the name is not absolute, and removes any leading «/» if the name is absolute. It is possible, though uncommon, to have classes in diffent packages sharing the same resource.
Using Methods of java.lang.ClassLoader
The ClassLoader class has two sets of methods to access resources. One set returns an InputStream for the resource. The other set returns a URL. The methods that return an InputStream are easier to use and will satisfy many needs, while the methods that return URLs provide access to more complex information, such as an Image and an AudioClip.
The ClassLoader manges resources similarly to the way it manages classes. A ClassLoader controls how to map the name of a resource to its content. ClassLoader also provides methods for accessing system resources, analogous to the system classes. The Class class provides some convenience methods that delegate functionality to the ClassLoader methods.
Many Java programs will access these methods indirectly through the I18N (localization) APIs. Others will access it through methods in Class . A few will directly invoke the ClassLoader methods.
The methods in ClassLoader use the given String as the name of the resource without applying any absolute/relative transformation (see the methods in Class). The name should not have a leading «/».
System resources are those that are handled by the host implemenation directly. For example, they may be located in the CLASSPATH.
The name of a resource is a «/»-separated sequence of identifiers. The Class class provides convenience methods for accessing resources; the methods implement a convention where the package name is prefixed to the short name of the resource.
Resources can be accessed as an InputStream , or a URL.
The getSystemResourceAsStream method returns an InputStream for the specified system resource or null if it does not find the resource. The resource name may be any system resource.
The getSystemResource method finds a system resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java.net.URL.getContent() with the URL will return an object such as ImageProducer , AudioClip , or InputStream .
The getResourceAsStream method returns an InputStream for the specified resource or null if it does not find the resource.
The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java.net.URL.getContent() with the URL will return an object such as ImageProducer , AudioClip , or InputStream .
Security
Since getResource() provides access to information, it must have well-defined and well-founded security rules. If security considerations do not allow a resource to be visible in some security context, the getResource() method will fail (return null) as if the resource were not present at all, this addresses existence attacks.
ClassLoader.getResource and ClassLoader.getSystemResource() and extend to the AsStream methods as defined in the previous section. —>
Class loaders may not provide access to the contents of a .class file for both security and performance reasons. Whether it is possible to obtain a URL for a .class file depends on the specifics, as shown below.
There are no specified security issues or restrictions regarding resources that are found by a non-system class loader. AppletClassLoader provides access to information that is loaded from a source location, either individually, or in a group through a JAR file; thus AppletClassLoader should apply the same checkConnect() rules when dealing with URLs through getResource() .
The system ClassLoader provides access to information in the CLASSPATH. A CLASSPATH may contain directories and JAR files. Since a JAR file is created intentionally, it has a different significance than a directory where things may end up in a more casual manner. In particular, we are more strict on getting information out of a directory than out from a JAR file.
If a resource is in a directory:
- getResource() invocations will use File.exists() to determine whether to make the corresponding file visible to the user. Recall that File.exists() uses the checkRead() method in the security manager.
- the same applies to getResourceAsStream() .
If the resource is in a JAR file:
- getResource() invocations will succeed for all files, regardless of whether the invocation is done from within a system or a non-system class.
- getResourceAsStream() invocations will succeed for non .class resources, and so will for java.net.URL.getContent() on corresponding URLs.
Examples
This section provides two examples of client code. The first example uses «absolute resource» names and traditional mechanisms to get a Class object.
This example uses «relative resource» names and the mechanism available from the compiler through the -experimental flag, to get a Class object.
Java как указать путь к файлу из resources
В этой статье будет показано, как прочитать файл из папки “ресурсы”, “getResourceAsStream” или “getResource”.
- Автор записи
Автор оригинала: mkyong.
В Java мы можем использовать getResourceAsStream или getResource для чтения файла или нескольких файлов из папки ресурсы или корневого каталога пути к классу.
Метод getResourceAsStream возвращает Входной поток .
Метод getResource возвращает URL и обычно преобразует его в Файл ; Не работает в файле JAR .
1. Файлы в ресурсах папка
1.1 Просмотрите файлы в src/main/ресурсы , позже мы получим доступ к файлам и распечатаем содержимое файла.
1.2 По умолчанию инструменты сборки, такие как Maven, Gradle или обычная практика Java, будут копировать все файлы из src/основные/ресурсы в корневой каталог целевые/классы или сборка/классы . Итак, когда мы пытаемся прочитать файл из src/main/ресурсы , мы читаем файл из корневого каталога пути к классам проекта.
1.3 Ниже приведена структура файла JAR. Обычно файлы в папке ресурсы копируются в корневой каталог пути к классу.
2. Получите файл из папки ресурсов.
2.1 Приведенный ниже пример демонстрирует использование getResourceAsStream и getResource методы чтения файла json/файл 1.json из папки ресурсы
- Метод getResource не работает в файле JAR.
- Метод getResourceAsStream работает везде.
2.2 Теперь мы упаковываем проект в файл JAR и запускаем его; на этот раз getResource завершится ошибкой и вернет либо Исключение NoSuchFileException , либо Исключение InvalidPathException . Мы не можем прочитать файлы внутри файла JAR по URL-адресу ресурса.
Запустите файл JAR в Linux (Ubuntu), он вызовет Исключение NoSuchFileException .
Запустите файл JAR в Windows, он вызовет Исключение InvalidPathException .
P.S В этом примере используется плагин Maven maven-jar-плагин чтобы создать файл JAR.
3. Получите файл из папки ресурсов – Модульный тест
3.1 Мы помещаем тестовые ресурсы в папку src/test/ресурсы для модульных тестов. Обычно файлы в тестовых ресурсах копируются в папку target/test-classes .
3.2 Это работает так же, как мы читаем файл из src/main/ресурсы . Мы используем то же самое getResourceAsStream и getResource методы чтения файла из src/test/ресурсов .
4. Получите все файлы из папки ресурсов. (Среда, ОТЛИЧНАЯ от JAR)
Если мы не знаем точного имени файла и хотим прочитать все файлы, включая файлы вложенных папок из папки ресурсов, мы можем использовать NIO Файлы.перейдите , чтобы легко получить доступ к файлам и прочитать их.
4.1 В приведенном ниже примере используются Файлы.пройдите чтобы прочитать все файлы из папки src/основные/ресурсы/json :
4.2 Однако стандартные Файлы.прогулка в примере 4.1 не удается получить доступ к файлам в файле JAR напрямую, попробуйте запустить пример 4.1 в среде JAR, и он выдает Исключение FileSystemNotFoundException .
Read a File from Resources Directory
Learn to read a file from the resources folder in a Java application. We will learn to read the file present inside the jar file, and outside the Jar file as well. A file outside the jar file may be present as a war file or an Eclipse project in the development environment.
1. Packaging a File into resources Folder
The resources folder belongs to the Maven project structure where we place the configuration and data files related to the application. The location of the folder can be “ src/main/resources ” and “ src/test/resources “.
- When packaging the application as jar file, the file present in the ‘/resources’ folder are copied into the root ‘target/classes’ folder. In this case, the file location is inside a zipped archive like jar-filename.jar/!filename.txt . We should directly read this file as InputStream .
- When packaging the application as war file, the file present in the ‘/resources’ folder are copied into the root ‘/target/app-name’ folder. After the deployment in an application server, the war files are extracted in a server work directory. So, in this case, we are reading the file outside a zipped archive so we can refer to the file using a relative path. We can refer to this file using File instance and can use any suitable method to read the file content.
In the given examples, we read two files in the /resources folder. The first file /demo.txt is at the root of /resources folder. The second file /data/demo.txt folder is inside a nested folder /data in the resources folder.
The file locations in the resources folder
2. Resources Packaged as .jar File
2.1. Using ClassLoader.getResourceAsStream()
Use the getResourceAsStream() method to get the InputStream when reading a file from inside a jar file. Always use this method on the ClassLoader instance.
This code works on the development environment also.
2.2. Complete Example
Once we have the InputStream reference, we can use it to read the file content or pass it to any resource handler class.
2.3. How to test the code
To test the above code, package the application as jar file using ‘mvn clean package’ command. Also, provide the ‘mainClass’ attribute to maven-jar-plugin and set its value to the class which has main() method and the test code.
Now, run the main() method from the console.
3. Resources Packaged as .war File
3.1. Using ClassLoader.getResource()
Use the getResource() method to get the File instance when reading a file from inside a war file. I suggest using this method on the ClassLoader instance.
3.2. Complete Example
Now use the File reference to read the file content.
3.3. How to test the code
To test the above code, package the application as a war file using mvn clean package command. Use the maven-resources-plugin plugin to copy the files from the resources folder to the root of the war file archive.
Now, run the main method from the console. Do not forget to add the classes to the classpath.
Как получить абсолютный путь к файлу в папке / resources в вашем проекте
В Java, как я могу получить абсолютный путь к файлу, пожалуйста?
4 ответа
Вы можете создать объект File и использовать метод getAbsolutePath :
Правильный способ работы:
Теперь не имеет значения, где физически находится файл в пути к классам, он будет найден до тех пор, пока ресурс фактически является файлом, а не записью JAR.
(Казалось, очевидный new File(resource.getPath()) не работает для всех путей! Путь по-прежнему кодируется URL-адресом!)
создать класс classLoader, тогда вы можете легко получить доступ к файлам или ресурсам. теперь вы получаете доступ к пути, используя метод getPath() этого класса.
Read a File from Resources Folder in Java
This tutorial illustrates How to read a file from Classpath or Resources Folder in Java using File IO, NIO, and FileChannel.
Overview
All Maven and Gradle projects follow Maven’s standard directory structure (link), which helps segregate different types of source files in dedicated directories. Application-level configurations (like Properties and YAML) and other files reside in the resources directory.
- src/main/resources – A place to keep Application level resources and files.
- src/test/resources – A place to keep resources and files for the test purpose.
Java provides several ways to read the files from the resources directory. The following tutorial covers examples of reading files from ‘src/main/resources‘ or ‘src/test/resources‘ directory.
Using Plain Java – getResourceAsStream()
Java Class class provides the getResourceAsStream() method that can open an InputStream to a file in the classpath.
To read a file from the ‘src/main/resources‘ we need to provide a file path relative to this directly. When we invoke getResourceAsStream() in a unit test, it reads the file from ‘src/test/resources‘ directory.
We can now use the InputStream instance to read the file’s contents.
Firstly, we use the Class.getResourceAsStream() method to retrieve an InputStream to the intended file. Then we create an InputStreamReader instance to build a BufferedReader instance. The BufferedReader‘s lines() method provides a Java Stream of the lines from the file.
The lines() method of the BufferedReader is lazy. This means it reads lines if we consume the stream.
Note that we are using try-with-resources that automatically helps us close various File IO resources and streams.
Alternatively, we can use getResourceAsStream on the class loader.
The difference between the two is that using getResourceAsStream() on the Class instance is relative to the resources folder. Thus, we added a slash (/) to the path. On the other hand, getResourceAsStream() on the class loader instance takes an absolute path, which is why we have not added the slash (/).
Using FileReader
We can create a FileReader instance by providing the file’s path relative to the project root. We can then wrap the FileReader into a BufferedReader instance and use the BufferedReader to read the file in a Stream of lines.
Example of using the FileReader to read a file from the resources directory
Using Files.newBufferedReader()
Java NIO’s Files class provides a static method, newBufferedReader(), that we can use to build a BufferedReader instance. To do so, we must give the file’s path relative to the project root.
Example of using the newBufferedReader() method from Java NIO Files class to read a file from the resources directory.
Using Files.lines()
Alternatively, the more straightforward way is to use the Java NIO Files class’s lines() method. The lines() method accepts the file’s path relative to the project root directory. It returns a Java Stream of the lines from the file.
Example of using the lines() method of Java NIO Files to read a file from the “src/main/resources” or “src/test/resources” directory.
Using DataInputStream
We can also combine the Java Class’s getResourceAsStream() method with an DataInputStream instance to read a file from the resources directory or classpath.
Example of using the DataInputStream to read a file from the resources folder.
Firstly, we used the getResourceAsStream() method to create an InputStream to the file from resources directory. Next, we wrapped the InputStream instance into a DataInputStream instance. The DataInputStream is useful for reading primitive java data types from a file.
Using FileChannel
Using FileChannel to read a file from the resources diretory is fastest of all the ways, especially when the file is large.
Example of using the FileChannel to read a file from “src/main/resources” or “src/test/resources” directory.
To obtain a FileChannel mapped to our file, we first create a RandomAccessFile instance. We can then use the FileChannel instance to read the file chunk by chunk.
Summary
In this detailed tutorial, we have learned different ways of reading a file from the resources directory (“src/main/resources” or “src/test/resources” folders) or classpath. We went through the examples of reading a files using the plain Java, Java NIO, and FileChannel.
Read a File from Resources Directory
Learn to read a file from the resources folder in a Java application. We will learn to read the file present inside the jar file, and outside the Jar file as well. A file outside the jar file may be present as a war file or an Eclipse project in the development environment.
1. Packaging a File into resources Folder
The resources folder belongs to the Maven project structure where we place the configuration and data files related to the application. The location of the folder can be “ src/main/resources ” and “ src/test/resources “.
- When packaging the application as jar file, the file present in the ‘/resources’ folder are copied into the root ‘target/classes’ folder. In this case, the file location is inside a zipped archive like jar-filename.jar/!filename.txt . We should directly read this file as InputStream .
- When packaging the application as war file, the file present in the ‘/resources’ folder are copied into the root ‘/target/app-name’ folder. After the deployment in an application server, the war files are extracted in a server work directory. So, in this case, we are reading the file outside a zipped archive so we can refer to the file using a relative path. We can refer to this file using File instance and can use any suitable method to read the file content.
In the given examples, we read two files in the /resources folder. The first file /demo.txt is at the root of /resources folder. The second file /data/demo.txt folder is inside a nested folder /data in the resources folder.
The file locations in the resources folder
2. Resources Packaged as .jar File
2.1. Using ClassLoader.getResourceAsStream()
Use the getResourceAsStream() method to get the InputStream when reading a file from inside a jar file. Always use this method on the ClassLoader instance.
This code works on the development environment also.
2.2. Complete Example
Once we have the InputStream reference, we can use it to read the file content or pass it to any resource handler class.
2.3. How to test the code
To test the above code, package the application as jar file using ‘mvn clean package’ command. Also, provide the ‘mainClass’ attribute to maven-jar-plugin and set its value to the class which has main() method and the test code.
Now, run the main() method from the console.
3. Resources Packaged as .war File
3.1. Using ClassLoader.getResource()
Use the getResource() method to get the File instance when reading a file from inside a war file. I suggest using this method on the ClassLoader instance.
3.2. Complete Example
Now use the File reference to read the file content.
3.3. How to test the code
To test the above code, package the application as a war file using mvn clean package command. Use the maven-resources-plugin plugin to copy the files from the resources folder to the root of the war file archive.
Now, run the main method from the console. Do not forget to add the classes to the classpath.