spring spring中读取txt文件的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10202494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:05:19  来源:igfitidea点击:

method in spring to read txt file

springfile-io

提问by ankit rai

I am having a requirement wherein I need to read the contents of a text file through spring framework. For this purpose I made a method in my service implementation class as below-

我有一个要求,我需要通过 spring 框架读取文本文件的内容。为此,我在我的服务实现类中创建了一个方法,如下所示 -

public String readFile(File file)

This method will take the file name as input and read the file.

此方法将文件名作为输入并读取文件。

I was writing the code in XML for spring as below-

我正在为 spring 编写 XML 代码,如下所示 -

<bean id="fstream" class="java.io.FileInputStream">
    <constructor-arg value="C:/text.txt" />
</bean>
<bean id="in" class="java.io.DataInputStream">
    <constructor-arg ref="fstream"/>
</bean>
<bean id="isr" class="java.io.InputStreamReader">
    <constructor-arg ref="in"/>
</bean>
<bean id="br" class="java.io.BufferedReader">
    <constructor-arg ref="isr"/>
</bean>

Following code goes in my method-

以下代码在我的方法中-

public String readFile(File file)
{
    String line = null;
    String content = "";

    try
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("FileDBJob.xml");

        BufferedReader br = (BufferedReader) context.getBean("br");

        while((line = br.readLine())!=null)
            content = content.concat(line);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return content;
}

But here the issue is that i need to hardcode the file name in XML, so there is no use of file parameter.

但这里的问题是我需要在 XML 中对文件名进行硬编码,因此没有使用 file 参数。

Kindly help in finding the solution. As I am new to spring and trying my hands with it so it may be possible that I am missing something. Any help would be of great help.

请帮助寻找解决方案。由于我是春天的新手并尝试使用它,所以我可能会遗漏一些东西。任何帮助都会有很大帮助。

回答by Greg Case

Don't inject the streams and readers, that's not really how Spring is intended to be used. I'd inject the file itself:

不要注入流和读取器,这不是 Spring 的真正用途。我会注入文件本身:

public class MyFileReader {

    private File file;

    public String readFile() {
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(getFile()));
            String line = null;
            while ((line = reader.readLine()) != null)
                builder.append(line);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeQuietly(reader);
        }
        return builder.toString();
    }

    private void closeQuietly(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException ignored) {}
        }
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

}

Then your bean def looks like this:

然后你的 bean def 看起来像这样:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location" value="classpath:app.properties"/>
</bean>

<bean class="com.myapp.MyFileReader">
    <property name="file" value="${filePath}" />
</bean>

All that is left is to create your app.properties file with the correct info. You can also set the value by invoking the app with a -DfilePath=/foo/bar/whatever.txt

剩下的就是用正确的信息创建你的 app.properties 文件。您还可以通过调用应用程序来设置值-DfilePath=/foo/bar/whatever.txt

回答by Ramchandar T

I have tested this code its working..... Try to implement....you have to copy paste schedular.xml file in ur proj configuration folder(where applicationContext.xml file in ur application and it has to be contextConfigLocation WEB-INF/config/*.xml in ur web.xml file).

我已经测试了这段代码的工作..... 尝试实现....你必须在你的项目配置文件夹中复制粘贴 schedular.xml 文件(你的应用程序中的 applicationContext.xml 文件,它必须是 contextConfigLocation WEB-您的 web.xml 文件中的 INF/config/*.xml)。

Then configure SvhedularTask bean in ur service classes xml file....it will trigger for every minute.

////SCHEDULARTASK.JAVA//////

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletContext;

import org.springframework.web.context.ServletContextAware;


/**
 * The Class SchedulerTask.
 */
public class SchedulerTask implements ServletContextAware{

    private ServletContext servletContext;

    @Override
    public void setServletContext(ServletContext arg0) {
        // TODO Auto-generated method stub
        this.servletContext = arg0;
    }

    public void unZipProcess() throws IOException{
        System.out.println(servletContext);
        File folder = new File("C:/Users/rerrabelli/Desktop/test");
        File[] listOfFiles = folder.listFiles();
        if (listOfFiles != null){
            for (int i = 0; i < listOfFiles.length; i++) {
                if (listOfFiles[i].isFile()) {
                    if (listOfFiles[i].getName().endsWith(".txt")) {
                        File file = new File("C:/Users/rerrabelli/Desktop/test" + File.separator
                                + listOfFiles[i].getName());
                        long millisec = file.lastModified();
                        Date dt = new Date(millisec);
                        long difference = new Date().getTime()-dt.getTime();
                        System.out.println((difference/1000)/60);
                        if(((difference/1000)/60)<1){
                            FileInputStream fin = new FileInputStream(
                                    file);
                            ByteArrayOutputStream tmp = new ByteArrayOutputStream();
                            byte b;
                            while ((b = (byte) fin.read()) != -1) {
                                tmp.write(b);
                            }
                            byte[] customerData = tmp.toByteArray();
                            String data = new String(customerData);
                            System.out.println(data);
                            servletContext.setAttribute(file.getName(), data);
                        }
                    }
                }
            }
        }
        System.out.println(servletContext.getAttribute("test.txt"));
    }

}

//////APPLICATION CONTEXT.xml/////////

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">



    <bean id="schedulerTask" class="com.altimetrik.simreg.service.impl.SchedulerTask">

    </bean>
</beans>

======================
SCHEDULAR.XML
===========
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd" >
<beans>

    <import resource="applicationContext.xml"/>

    <bean id="schedulerTask1"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject"> <ref bean="schedulerTask" /> </property>
        <property name="targetMethod"> <value>unZipProcess</value> </property>
        <property name="concurrent"> <value>false</value> </property>
    </bean>

    <bean id="UnzipTrigger"
        class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail"> <ref bean="schedulerTask1" /> </property>
        <property name="cronExpression"> <value>0 0/1 * * * ?</value> </property>
    </bean>

    <bean
        class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <!-- Add triggers here-->
                <ref bean="UnzipTrigger" />
            </list>
        </property>
    </bean>
</beans>