25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6 ■ Using Resource Files<br />

Listing 6-2. MyDocumentsTest.java<br />

package com.apress.isf.spring.test;<br />

import java.io.IOException;<br />

import java.io.InputStream;<br />

import java.util.Scanner;<br />

import org.junit.Before;<br />

import org.junit.Test;<br />

import org.springframework.context.support.ClassPathXmlApplicationContext;<br />

import org.springframework.core.io.Resource;<br />

public class MyDocumentsTest {<br />

private static final Logger log = LoggerFactory.getLogger(MyDocumentsTest.class);<br />

private ClassPathXmlApplicationContext context;<br />

@Before<br />

public void setup(){<br />

context = new ClassPathXmlApplicationContext("META-INF/spring/mydocuments-context.xml");<br />

}<br />

}<br />

@Test<br />

public void testMenu() {<br />

log.debug("About to read the Resource file: menu.txt ");<br />

Resource resource = context.getResource("classpath:META-INF/data/menu.txt");<br />

try{<br />

InputStream stream = resource.getInputStream();<br />

Scanner scanner = new Scanner(stream);<br />

while (scanner.hasNext()) {<br />

System.out.println(scanner.nextLine());<br />

}<br />

scanner.close();<br />

stream.close();<br />

}catch(IOException e){<br />

e.printStackTrace();<br />

}<br />

}<br />

The <strong>Spring</strong> <strong>Framework</strong> has a utility package, org.springframework.core.io, that contains several helpers for<br />

I/O operations, as shown in Listing 6-2. In your test, you are using the org.springframework.core.io.Resource class<br />

that will locate your resource file so you can print it out into the console. If you run your unit test using<br />

gradle :ch05:test<br />

62

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!