Interview Questions

Spring - Load Custom File

Custom files can be loaded in a Spring application using Spring Resource API.

Create a class LoadFile with a Resource member variable as follows.

LoadFile Class

public class LoadFile
{
  private Resource  file;

  public LoadFile()
  {
  }

  public Resource getFile()
  {
    return file;
  }

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

Now we need to inject any custom file to the LoadFile bean as follows

<bean id="loadFile" class="in.techdive.spring.examples.LoadFile">
    <property name="file" value="<file-path>" />
</bean>

When the Spring context loads initially, the resource is injected in to the loadFile bean. After that, we can perform all file manipulation read/write operations using the Resource interface.

The following is the complete code to read a custom file using spring resource interface.

LoadFile Class

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.spring.examples;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.Resource;

public class LoadFile
{
  private Resource  file;

  public LoadFile()
  {
  }

  public Resource getFile()
  {
    return file;
  }

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

  public void readFromFile() throws Exception
  {
    InputStream is = file.getInputStream();
    BufferedInputStream bi = new BufferedInputStream(is);
    StringBuffer sb = new StringBuffer();
    int read = 0;
    try
    {
      while ((read = bi.read()) != -1)
      {
        sb.append((char) read);
      }
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
    System.out.println(sb.toString());
  }

  public static void main(String[] args) throws Exception
  {
    ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[] { "classpath*:spring-LoadFile.xml" });
    LoadFile lFile = (LoadFile) ctx.getBean("loadFile");
    lFile.readFromFile();
  }
}