[Java] Get the file in the jar regardless of the environment

Introduction

For example, when you want to get a text template. If the development environment and the production are different (I think it's almost different), the absolute path is environment-dependent, isn't it? You can write the location for each environment to the property, but it is better to have a small setting value, and if possible, include it in the jar. So, this time it is a utility to get the resources in the jar.

Implementation

environment

FileUtil class

FileUtil.java


package jp.demo.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
	private static final String CHARSET_UTF8 = "UTF-8";
	private static final String LF = "\n";

	/**
	 *Return line by line in List. (Excluding line feed characters)
	 * @param string
	 * @return
	 * @throws IOException
	 */
	public static List<String> getTextLines(String string) throws IOException {
		List<String> list = new ArrayList<>();
		try (InputStream is = ClassLoader.getSystemResourceAsStream(string);
				BufferedReader br = new BufferedReader(new InputStreamReader(is, CHARSET_UTF8))) {
			String line;
			while ((line = br.readLine()) != null) {
				list.add(line);
			}
		}
		return list;
	}

	/**
	 *Return as a String. (Line feed code is LF)
	 * @param string
	 * @return
	 * @throws IOException
	 */
	public static String getTextStr(String string) throws IOException {
		StringBuilder sb = new StringBuilder();
		try (InputStream is = ClassLoader.getSystemResourceAsStream(string);
				BufferedReader br = new BufferedReader(new InputStreamReader(is, CHARSET_UTF8))) {
			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line + LF);
			}
		}
		return sb.toString();
	}
}

Main class

Main.java


package jp.demo;

import java.io.IOException;
import java.util.List;

import jp.demo.util.FileUtil;

public class Main {
	public static void main(String[] args) {
		System.out.println("### START ###");
		List<String> list = null;
		String str = null;
		try {
			list = FileUtil.getTextLines("jp/demo/text1.txt");
			str = FileUtil.getTextStr("jp/demo/text1.txt");
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("getTextLines:");
		list.forEach(System.out::println);
		System.out.println("\ngetTextStr:");
		System.out.println(str);

		System.out.println("### END ###");
	}
}

text file

Character code: UTF-8, line feed code: CRLF The following is saved in src / main / resources / jp / demo / text1.txt.

text1.txt


row1 test test
row2 ah
row3 Mr. Yamada

Run

Create a jar by maven install.

Execution result

I was able to get the text file with both methods.

Execution result


C:\sts\workspace\simple_maven\target>java -jar test-0.0.1-SNAPSHOT.jar
### START ###
getTextLines:
row1 test test
row2 ah
row3 Mr. Yamada

getTextStr:
row1 test test
row2 ah
row3 Mr. Yamada

### END ###

C:\sts\workspace\simple_maven\target>

This is the case when the text is saved in the character code SJIS. ↓

Execution result


C:\sts\workspace\simple_maven\target>java -jar test-0.0.1-SNAPSHOT.jar
### START ###
getTextLines:
row1 test test
row2 ??????
row3 ?R?c????

getTextStr:
row1 test test
row2 ??????
row3 ?R?c????

### END ###

C:\sts\workspace\simple_maven\target>

I read the SJIS text in UTF-8, so the characters were garbled. Then, when a character that does not exist in SJIS (the famous one is Takahashi's "Taka") is output as a file with the character set SJIS, it is replaced with "?".

Digression

On Eclipse, Maven projects are src / main / ** java **, src / main / ** resources ** However, once you build it, it will be the same, so it is the same regardless of where you save the text.

Expand the jar and jp/demo/Look under


C:\Users\xxx\Desktop\test-0.0.1-SNAPSHOT\jp\demo directory

2019/06/12  00:57    <DIR>          .
2019/06/12  00:57    <DIR>          ..
2019/06/12  00:27             1,815 Main.class
2019/06/11  01:39                26 text1.txt
2019/06/12  00:57    <DIR>          util

Recommended Posts

[Java] Get the file in the jar regardless of the environment
Get the public URL of a private Flickr file in Java
How to get the length of an audio file in java
JAVA: jar, aar, view the contents of the file
Get the URL of the HTTP redirect destination in Java
[Java] Get the file path in the folder with List
Replace the contents of the Jar file
Examine the system information of AWS Lambda operating environment in Java
[Java] Get the dates of the past Monday and Sunday in order
[Java] Get the day of the specific day of the week
How to get the date in java
The story of writing Java in Emacs
[Java8] Search the directory and get the file
Sample program that returns the hash value of a file in Java
How to get the absolute path of a directory running in Java
[Java] Get MimeType from the contents of the file with Apathce Tika [Kotlin]
The story of low-level string comparison in Java
The story of making ordinary Othello in Java
About the idea of anonymous classes in Java
The story of learning Java in the first programming
Measure the size of a folder in Java
[Java] Get the length of the surrogate pair string
Feel the passage of time even in Java
Rename the package name of the existing jar file
[Java] Read the file in src / main / resources
[Java] How to get the authority of the folder
Import files of the same hierarchy in Java
How to set environment variables in the properties file of Spring boot application
Sample code to get the values of major SQL types in Java + MySQL 8.0
[Java] How to get the URL of the transition source
Access the war file in the root directory of Tomcat
Get the name of the test case in the JUnit test class
Include image in jar file with java static method
[Java] How to get the maximum value of HashMap
Source used to get the redirect source URL in Java
Change the storage quality of JPEG images in Java
How to debug the generated jar file in Eclipse
SSL in the local environment of Docker / Rails / puma
Get the URL of the HTTP redirect destination in Ruby
Summarize the additional elements of the Optional class in Java 9
[Java] Integer information of characters in a text file acquired by the read () method
How to get the class name of the argument of LoggerFactory.getLogger when using SLF4J in Java
Easily monitor the indoor environment ~ ⑨ Get motion detection (HC-SR501 / RCWL-0516) in Java (GPIO / Pi4J) ~
[Java] [Maven] Template of pom.xml to register 3rd party jar file in local repository
Get EXIF information in Java
[Java] Get KClass in Java [Kotlin]
JavaFX environment construction in Java 13
Implementation of gzip in java
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
Implementation of tri-tree in Java
How to get the class name / method name running in Java
Was done in the base year of the Java calendar week
Generate and execute Jar file of Java file belonging to package
A quick explanation of the five types of static in Java
Get the next business day after the specified date in JAVA
Put the file in the properties of string in spring xml configuration
Get to the abbreviations from 5 examples of iterating Java lists
Install by specifying the version of Django in the Docker environment
Activate Excel file A1 cell of each sheet in Java
Count the number of digits after the decimal point in Java
Get attributes and values from an XML file in Java