Sunday 6 March 2022

Java: Get the content of resource file as string

Following snippet return the content of resource file as string.

 

 


Find the below working application.

 

ResourceFileAsString.java

package com.sample.app.files;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class ResourceFileAsString {
	public static String resourceAsString(String resourceName) throws IOException {
		ClassLoader classLoader = ResourceFileAsString.class.getClassLoader();
		URL url = classLoader.getResource(resourceName);
		if (url == null) {
			return null;
		}

		URLConnection urlConnection = url.openConnection();

		urlConnection.setUseCaches(false);

		try (InputStreamReader inputStreamReader = new InputStreamReader(urlConnection.getInputStream())) {
			char[] buffer = new char[1048];
			StringBuilder builder = new StringBuilder();

			int count = -1;
			while ((count = inputStreamReader.read(buffer, 0, buffer.length)) != -1) {
				builder.append(buffer, 0, count);
			}

			return builder.toString();
		}

	}

	public static void main(String args[]) throws IOException {
		String output = resourceAsString("file.txt");
		System.out.println(output);

	}
}

You may like

File programs in Java

List files by their created time

Create file parent directories if they are not exist

Get file name from absolute path

Count number of lines in a file

Download file from Internet using Java


No comments:

Post a Comment