Java как указать путь к файлу из resources

от admin

Интерфейс Resource

Стандартный класс java.net.URL и стандартные обработчики различных префиксов URL в Java, к сожалению, не достаточно подходят для обеспечения доступа ко всем низкоуровневым ресурсам. Например, не существует стандартизированной реализации URL , которую можно использовать для получения доступа к ресурсу, который нужно получить из пути классов или относительно ServletContext . Хотя можно зарегистрировать новые обработчики для специализированных префиксов URL (аналогично существующим обработчикам для таких префиксов, как http: ), это обычно довольно сложно, а интерфейсу URL все еще не будет хватает некоторых желательных функций, таких как метод проверки существования ресурса, на который указывают.

Интерфейс Resource

Интерфейс Resource фреймворка Spring, расположенный в пакете org.springframework.core.io. предназначен для абстрагирования доступа к низкоуровневым ресурсам. В следующем листинге кратко представлен интерфейс Resource . Более подробную информацию см. в javadoc по Resource .

Как видно из определения интерфейса Resource , он расширяет интерфейс InputStreamSource . В следующем листинге показано определение интерфейса InputStreamSource :

Некоторыми из наиболее важных методов интерфейса Resource являются:

getInputStream() : Находит и открывает ресурс, возвращая InputStream для считывания из ресурса. Предполагается, что каждый вызов возвращает новый InputStream . Ответственность за закрытие потока лежит на вызывающем коде.

exists() : Возвращает булево значение boolean , указывающее, существует ли данный ресурс в физической форме.

isOpen() : Возвращает булево значение boolean , указывающее, представляет ли данный ресурс дескриптор (хэндл) с открытым потоком. Если true , то InputStream не может быть считан несколько раз и должен быть считан только единожды, а затем закрыт, чтобы избежать утечки ресурсов. Возвращает false для всех стандартных реализаций ресурсов, за исключением InputStreamResource .

getDescription() : Возвращает описание для этого ресурса, которое будет использоваться для вывода ошибок при работе с ресурсом. Часто это полностью уточненное имя файла или фактический URL ресурса.

Другие методы позволяют получить фактический URL или объект File , представляющий ресурс (если базовая реализация совместима и поддерживает эту функциональность).

Некоторые реализации интерфейса Resource также реализуют расширенный интерфейс WritableResource для ресурса, который поддерживает запись в него.

Сам Spring широко использует абстракцию Resource в качестве типа аргумента во многих сигнатурах методов, когда требуется какой-либо ресурс. Другие методы в некоторых API-интерфейсах Spring (например, конструкторы различных реализаций ApplicationContext ) принимают String , которая без дополнений или в простом виде используется для создания Resource , соответствующего данной реализации контекста, или при помощи специальных префиксов на пути к String позволяет вызывающему коду задать создание и использование конкретной реализации Resource .

Хотя интерфейс Resource часто используется в Spring и самим Spring, на самом деле его очень удобно использовать в качестве общего служебного класса в собственном коде для получения доступа к ресурсам, даже если ваш код не знает о других частях Spring и не реализует их. Хотя это и привязывает ваш код к Spring, на самом деле такого рода привязка осуществляет только с этим небольшим набором служебных классов, который служит более функциональной заменой URL и может считаться эквивалентным любой другой библиотеке, которую вы бы использовали для этой цели.

Встроенные реализации Resource

Spring включает в себя несколько встроенных реализаций Resource :

Полный список реализаций Resource , доступных в Spring, можно найти в разделе «Все известные реализации классов» в javadoc по Resource .

UrlResource

UrlResource оборачивает java.net.URL и может быть использован для получения доступа к любому объекту, доступ к которому в обычных обеспечивается с помощью URL, например, к файлам, целевому элементу HTTPS, целевому элементу FTP и другому. Все URL-адреса имеют стандартизированное String представление, поэтому для обозначения одного типа URL-адреса от другого используются соответствующие стандартизированные префиксы. К ним относятся file: для доступа к путям файловой системы, https: для доступа к ресурсам по протоколу HTTPS, ftp: для доступа к ресурсам по протоколу FTP и другие.

UrlResource создается кодом Java путем явного использования конструктора UrlResource , но зачастую создается и неявно, если вызывать метод API-интерфейса, который принимает аргумент String , предназначенный для представления пути. В последнем случае PropertyEditor класса JavaBeans в конечном итоге решает, какой тип Resource создать. Если строка пути содержит известный (имеется в виду редактору свойств) префикс (например, classpath: ), то создается соответствующий специализированный Resource для этого префикса. Однако, если он не распознает префикс, он принимает строку за стандартную строку URL и создает UrlResource .

ClassPathResource

Этот класс представляет ресурс, который нужно получить из classpath. Для загрузки ресурсов используется либо загрузчик контекстных классов потока, либо данный загрузчик классов, либо данный класс.

Эта реализация Resource поддерживает разрешение как java.io.File , если ресурс пути классов находится в файловой системе, но не для ресурсов classpath, которые находятся в jar и не были развернуты (движком сервлета или какой-либо другой средой) в файловую систему. Чтобы решить эту проблему, различные реализации Resource всегда имеют поддержку выполнения разрешения в виде java.net.URL .

ClassPathResource создается в коде Java с помощью конструктора ClassPathResource , но зачастую создается и неявно, если вызывать метод API-интерфейса, который принимает аргумент String , предназначенный для представления пути. Для последнего случая PropertyEditor класса JavaBeans распознает специальный префикс classpath: в строке пути и в этом случае создает ClassPathResource .

FileSystemResource

Это реализация Resource , предназначенная для дескрипторов экземпляров класса java.io.File . Он также поддерживает обработку java.nio.file.Path , применяя стандартные для Spring преобразования путей на основе строк, но выполняя все операции через API-интерфейс java.nio.file.Files . Для чистой поддержки на основе java.nio.path.Path используйте вместо этого PathResource . FileSystemResource поддерживает разрешение и в виде File , и в виде URL .

PathResource

Это реализация интерфейса Resource , предназначенная для дескрипторов java.nio.file.Path , выполняющая все операции и преобразования через API-интерфейс Path . Данная реализация поддерживает разрешение как File и как URL , а также реализует расширенный интерфейс WritableResource . PathResource фактически является чистой альтернативой FileSystemResource , основанной на java.nio.path.Path , с иной логикой работы createRelative .

ServletContextResource

Это реализация Resource для ресурсов ServletContext , которая интерпретирует относительные пути в корневом каталоге соответствующего веб-приложения.

Она всегда поддерживает потоковый доступ и доступ по URL, но также предоставляет доступ по java.io.File только в том случае, если архив веб-приложения развернут, а ресурс физически находится в файловой системе. Будет ли он развернут в файловой системе, будет ли он доступен непосредственно из JAR или откуда-то еще, например, из базы данных (что вполне возможно), на самом деле зависит от контейнера сервлетов.

InputStreamResource

InputStreamResource – это реализация Resource для данного InputStream . Её следует использовать только в том случае, если не применима конкретная реализация Resource . В частности, отдавайте предпочтение ByteArrayResource или любой из реализаций Resource , основанных на файлах, где это возможно.

В отличие от других реализаций Resource , это дескриптор для уже открытого ресурса. Поэтому он возвращает true из функции isOpen() . Не используйте её, если вам необходимо где-то хранить дескриптор ресурса или если вам нужно считать поток несколько раз.

ByteArrayResource

Это реализация Resource , предназначенная для заданного байтового массива. Создает ByteArrayInputStream для заданного байтового массива.

Она полезна для загрузки содержимого из любого заданного байтового массива без необходимости использования одноразового InputStreamResource .

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 “ / “.

Java как указать путь к файлу из 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.

Читать:
Как открыть файл edoc

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.

Как получить абсолютный путь к файлу в папке / resources в вашем проекте

В Java, как я могу получить абсолютный путь к файлу, пожалуйста?

4 ответа

Вы можете создать объект File и использовать метод getAbsolutePath :

Правильный способ работы:

Теперь не имеет значения, где физически находится файл в пути к классам, он будет найден до тех пор, пока ресурс фактически является файлом, а не записью JAR.

(Казалось, очевидный new File(resource.getPath()) не работает для всех путей! Путь по-прежнему кодируется URL-адресом!)

создать класс classLoader, тогда вы можете легко получить доступ к файлам или ресурсам. теперь вы получаете доступ к пути, используя метод getPath() этого класса.

Похожие статьи