spring 读取操作系统上的文件

来源:互联网 发布:中国历史延续 知乎 编辑:程序博客网 时间:2024/04/30 12:36
package com.test.spring.beans;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


import org.springframework.context.ApplicationContext;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;


public class BannerLoader implements ResourceLoaderAware {


    private ResourceLoader resourceLoader;


    public void setResourceLoader(ResourceLoader rl) {
        this.resourceLoader = rl;
    }


    public void showBanner() throws IOException {
        Resource banner = resourceLoader.getResource("file:D:/bb.txt");
        InputStream in = banner.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        while (true) {
            String line = reader.readLine();
            if (null == line) {
                break;
            }
            System.out.println(line);
        }
        reader.close();
    }
    public static void main(String args[]) throws IOException {
        ApplicationContext appContext = new ClassPathXmlApplicationContext(
                new String[] { "applicationContext.xml" });
        BannerLoader banner = (BannerLoader) appContext.getBean("banner");
        banner.showBanner();
    }
}
0 0
原创粉丝点击