Java Read Open File Outside Src Folder

Learn to read a file from the resources folder in a Coffee application. We will learn to read the file present within the jar file; and outside the Jar file also.

A file outside the jar file may be present as a war file or an Eclipse project in the development environment.

Table of Contents  1. Packaging the file into resources binder 2. Reading file from resources folder packaged every bit .jar file 3. Reading file from resource binder packaged as .war file four. Reading file in Spring Application

one. Packaging the file into resource binder

The resources binder belongs to the maven project construction where we identify the configuration and information files related to the application. The location of the folder is "src/chief/resources".

  • When packaging the application every bit jar file, the file nowadays in the resources binder are copied in the root target/classes binder.
    In this case, the file location is inside a zipped archive like jar-filename.jar/!filename.txt. We should direct read this file as InputStream.
  • When packaging the awarding every bit war file, the file present in the resource folder are copied in the root target/app-name folder.
    After the deployment, war files are extracted in a server work ditrectory. And so, in this case, we are reading the file outside a zipped archive so we can refer the file using relative path. Nosotros can refer to this file using File instance and can utilise any suitable method to read the file content.

In the given examples, nosotros are reading two files present in the resource binder. The first file demo.txt is at the root of resource folder. The second file data/demo.txt binder is inside a nested folder data in the resources binder.

The file locations in the resources binder

2. Reading file from resources packaged as .jar file

2.1. ClassLoader.getResourceAsStream()

Use the getResourceAsStream() method to become the InputStream when reading a file from inside a jar file. Always use this method on the ClassLoader case.

          private InputStream getFileAsIOStream(final String fileName)  {     InputStream ioStream = this.getClass()         .getClassLoader()         .getResourceAsStream(fileName);          if (ioStream == null) {         throw new IllegalArgumentException(fileName + " is not found");     }     return ioStream; }        

2.2. Complete Example

In one case nosotros accept the InputStream reference, nosotros tin use it to read the file content or laissez passer information technology to whatever resources handler grade.

          package com.howtodoinjava.io;  import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader;  public class ReadFileFromResourcesUsingGetResourceAsStream  {     public static void primary(final String[] args) throws IOException      {         //Creating instance to avoid static member methods         ReadFileFromResourcesUsingGetResourceAsStream instance              = new ReadFileFromResourcesUsingGetResourceAsStream();          InputStream is = example.getFileAsIOStream("demo.txt");         instance.printFileContent(is);                  is = instance.getFileAsIOStream("information/demo.txt");         instance.printFileContent(is);     }      individual InputStream getFileAsIOStream(last String fileName)      {         InputStream ioStream = this.getClass()             .getClassLoader()             .getResourceAsStream(fileName);                  if (ioStream == null) {             throw new IllegalArgumentException(fileName + " is not found");         }         return ioStream;     }      private void printFileContent(InputStream is) throws IOException      {         attempt (InputStreamReader isr = new InputStreamReader(is);                  BufferedReader br = new BufferedReader(isr);)          {             Cord line;             while ((line = br.readLine()) != nothing) {                 System.out.println(line);             }             is.close();         }     } }        

2.3. How to test the code

To examination the above code, bundle the awarding as jar file using mvn clean package control. Also, provide the mainClass attribute to maven-jar-plugin and ready its value to the class which has main() method and the test code.

          <plugin> 	<groupId>org.apache.maven.plugins</groupId> 	<artifactId>maven-jar-plugin</artifactId> 	<version>three.2.0</version> 	<configuration> 		<archive> 			<manifest> 				<mainClass>com.howtodoinjava.io. 						ReadFileFromResourcesUsingGetResourceAsStream</mainClass> 			</manifest> 		</archive> 	</configuration> </plugin>        

Now, run the main() method from the console.

          mvn clean parcel java -jar target\app-build-name.jar        

iii. Reading file from resource folder packaged as .war file

3.1. ClassLoader.getResource()

Use the getResource() method to go the File instance when reading a file from inside a war file. I propose using this method on the ClassLoader case.

          private File getResourceFile(final String fileName)  {     URL url = this.getClass()         .getClassLoader()         .getResource(fileName);          if(url == null) {         throw new IllegalArgumentException(fileName + " is not establish one");     }          File file = new File(url.getFile());          return file; }        

three.2. Consummate Instance

Now utilise the File reference to read the file content.

          package com.howtodoinjava.io;  import coffee.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import coffee.internet.URL; import java.nio.file.Files;  public class ReadFileFromResourcesUsingGetResource {     public static void chief(final String[] args) throws IOException      {         //Creating instance to avert static member methods         ReadFileFromResourcesUsingGetResource instance              = new ReadFileFromResourcesUsingGetResource();          File file = example.getResourceFile("demo.txt");         case.printFileContent(file);                  file = case.getResourceFile("data/demo.txt");         example.printFileContent(file);     }      private File getResourceFile(terminal Cord fileName)      {         URL url = this.getClass()             .getClassLoader()             .getResource(fileName);                  if(url == naught) {             throw new IllegalArgumentException(fileName + " is not found 1");         }                  File file = new File(url.getFile());                  render file;     }      individual void printFileContent(File file) throws IOException      {         Cord content = new Cord(Files.readAllBytes(file.toPath()));         System.out.println(content);     }          private void printFileContent(InputStream is) throws IOException      {         try (InputStreamReader isr = new InputStreamReader(is);                  BufferedReader br = new BufferedReader(isr);)          {             String line;             while ((line = br.readLine()) != null) {                 Arrangement.out.println(line);             }             is.close();         }     } }        

iii.3. How to examination the code

To test the above code, parcel the application as a war file using mvn clean parcel command. Utilize the maven-resources-plugin plugin to copy the files from the resource folder to the root of the war file archive.

          <plugin> 	<groupId>org.apache.maven.plugins</groupId> 	<artifactId>maven-state of war-plugin</artifactId> 	<version>3.2.0</version> 	<configuration> 		<failOnMissingWebXml>false</failOnMissingWebXml> 	</configuration> </plugin> <plugin> 	<artifactId>maven-resource-plugin</artifactId> 	<version>2.4.iii</version> 	<executions> 		<execution> 			<id>copy-resources</id> 			<phase>process-resources</phase> 			<goals> 				<goal>copy-resource</goal> 			</goals> 			<configuration> 				<overwrite>true</overwrite> 				<outputDirectory>${project.build.directory} 					/${project.artifactId}-${projection.version}/</outputDirectory> 				<resource> 					<resources> 						<directory>${project.basedir}/src/main/resources</directory> 					</resource> 				</resources> 			</configuration> 		</execution> 	</executions> </plugin>        

Now, run the main method from the console. Practise not forget to add the classes to the classpath.

          mvn make clean package java -classpath "classes/." com.howtodoinjava.io.ReadFileFromResourcesUsingGetResource        

4. Reading file in Spring Application

If the application is a Spring WebMVC or Spring Boot application then we may have advantage of org.springframework.util.ResourceUtils class.

          File file = ResourceUtils.getFile("classpath:demo.txt")  //File is found System.out.println("File Found : " + file.exists());  //Read File Content Cord content = new String(Files.readAllBytes(file.toPath())); System.out.println(content);        

Happy Learning !!

cheeksacto1948.blogspot.com

Source: https://howtodoinjava.com/java/io/read-file-from-resources-folder/

0 Response to "Java Read Open File Outside Src Folder"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel