spring直接读取资源文件

只用spring的jar包,无需配置。C盘根目录下下放一份sample.txt文件

package resourceinjection;

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

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
/**
 * @author Apurav
 *
 */
public class BasicResourceSample {
	/**
	 * At the core, following are the utilities that can be used to get a
	 * resource. The Resource object returned by the following classes is a
	 * simple and handly object containing all the info of the resource 1. Using
	 * a url like http, ftp, file etc. We can use URLResource. This utility
	 * wraps the java.net.URL 2. Getting a file system resource using
	 * FileSystemResource. This wraps the java.io.File 3. ClasspathResource is
	 * used to get a resource from the classpath.
	 * 
	 */
	public static void main(String[] args) throws Exception {

		InputStream inputStream = null;
		Resource resource = null;
		//UrlResource sample/
		resource = new UrlResource("file:///C:/sample.txt");
		try {
			inputStream = resource.getInputStream();
			Scanner scanner0 = new Scanner(inputStream);
			while (scanner0.hasNext()) {
				System.out.println(scanner0.nextLine());
			}
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}

		//FileSystemResource sample

		try {
			resource = new FileSystemResource(
					"src/resourceinjection/sample.txt");
			inputStream = resource.getInputStream();
			Scanner scanner = new Scanner(inputStream);
			while (scanner.hasNext()) {
				System.out.println(scanner.nextLine());
			}
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}
 
		///ClassPathResource sample
		resource = new ClassPathResource("resourceinjection/sample.txt");
		try {
			inputStream = resource.getInputStream();
			Scanner scanner2 = new Scanner(inputStream);
			while (scanner2.hasNext()) {
				System.out.println(scanner2.nextLine());
			}
		} finally {
			if (inputStream != null) {
				inputStream.close();
			}
		}

	}

}

原文:http://simplespringtutorial.com/resourceinjection.html

源代码:http://pan.baidu.com/share/link?shareid=400505&uk=3878681452


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值