Spring read resource file from classpath :Sometime we are required to create file and read in to our application. Based on choice we can create file in anywhere inside project folder. Spring provide org.springframework.core.io.ClassPathResource API to read file which is available in classpath. Please see below java class which reads file from classpath:

SpringResourceFileRead.java

package com.javahonk;

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class SpringResourceFileRead {

    public static void main(String[] args) throws IOException {
	InputStream inputStream = null;
	Resource resource = null;
	Scanner scanner = null;
	try {
	    resource = new ClassPathResource(
		    "spring\\ResouceTestFile.txt");
	    inputStream = resource.getInputStream();
	    scanner = new Scanner(inputStream);
	    while (scanner.hasNext()) {
		System.out.println(scanner.nextLine());
	    }
	} finally {
	    if (null != inputStream) {
		inputStream.close();
	    }
	    if (null != scanner) {
		scanner.close();
	    }
	}

    }

}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *