2012-04-18 20 views
2

私は春のフレームワークを通してテキストファイルの内容を読む必要があります。この目的のために私はbelow-春のtxtファイルを読む方法

public String readFile(File file) 

として私のサービス実装クラスにメソッドを作られたこの方法は、入力としてファイル名を取り、ファイルを読み込みます。私は次のコード

<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> 

below-として春のためにXMLでコードを書いていた

は私の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; 
} 

に行くが、ここでの問題は、私は、ファイル名をハードコーディングする必要があるということですXMLでは、fileパラメータは使用されません。

解決策を見つけることを助けてください。私が春には新しいし、それで私の手を試すように、私は何かが欠けている可能性があります。どんな助けでも大きな助けになるでしょう。

+0

SpringframeworkのPropertyResolverまたはAbstractEnvironmentを見てください。 – andih

答えて

4

ストリームとリーダーを挿入しないでください。実際には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; 
    } 

} 

次に、あなたの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> 

すべてのことが残っているが、あなたのapp.propertiesが正しい情報を持つファイルを作成することです。 -DfilePath=/foo/bar/whatever.txt

+1

あなたの入力に感謝します。次のコードは私の問題を解決しました - FileSystemResource res = new FileSystemResource(file.getName()); BufferedReader br = new BufferedReader(新しいInputStreamReader(res.getInputStream())); while((line = br.readLine())!= null)content = content.concat(line); –

+0

Bean定義ファイルはどこに置くのですか? 'application-context.xml'または' spring-servlet.xml'ですか? –

0

私はこのコードをテストしています..... 実装しようとしています....あなたはur proj構成で貼り付けschedular.xmlファイルをコピーする必要がありますフォルダ(ここでapplicationContext.xmlファイルはurアプリケーション内にあり、ur web.xmlファイルには contextConfigLocation WEB-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> 
関連する問題