Spring read file on network

Spring read file on network : Sometimes files which is available on the network can be access using the url protocol like http://, ftp://, file:// etc… using UrlResource.

Below SpringResourceFileRead.java class will read file named ResourceTestFile.txt available locally on C drive. This can be access using file:// protocol shown below:

package com.javahonk;

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

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

public class SpringResourceFileRead {

    public static void main(String[] args) throws IOException {
	InputStream inputStream = null;
	Resource resource = null;
	Scanner scanner = null;
	try {
	    resource = new UrlResource("file:///C:/ResourceTestFile.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 *