From 82fd8bc677abeece738fb281f53439661254d981 Mon Sep 17 00:00:00 2001 From: Eugene Dzhurinsky Date: Wed, 3 Jun 2015 20:59:46 -0400 Subject: [ SI-7514 ] Introduce Source.fromClassPath(resource) method Creates Source from named classpath resource. Simplifies val src = io.Source.fromInputStream(classOf[ClassInst].getResourceAsStream("/name")) to val src = io.Source.fromClassPath("/name") --- src/library/scala/io/Source.scala | 10 ++++++++++ test/junit/scala/io/SourceTest.scala | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/src/library/scala/io/Source.scala b/src/library/scala/io/Source.scala index e38c197196..c0ee5f6a75 100644 --- a/src/library/scala/io/Source.scala +++ b/src/library/scala/io/Source.scala @@ -167,6 +167,16 @@ object Source { def fromInputStream(is: InputStream)(implicit codec: Codec): BufferedSource = createBufferedSource(is, reset = () => fromInputStream(is)(codec), close = () => is.close())(codec) + + /** Reads data from a classpath resource, using either a context classloader (default) or a passed one. + * + * @param resource name of the resource to load from the classpath + * @param classLoader classloader to be used, or context classloader if not specified + * @return the buffered source + */ + def fromResource(resource: String, classLoader: ClassLoader = Thread.currentThread().getContextClassLoader())(implicit codec: Codec): BufferedSource = + fromInputStream(classLoader.getResourceAsStream(resource)) + } /** An iterable representation of source data. diff --git a/test/junit/scala/io/SourceTest.scala b/test/junit/scala/io/SourceTest.scala index 3138a4589c..3fe48940a0 100644 --- a/test/junit/scala/io/SourceTest.scala +++ b/test/junit/scala/io/SourceTest.scala @@ -28,6 +28,10 @@ class SourceTest { @Test def canIterateLines() = { assertEquals(sampler.lines.size, (Source fromString sampler).getLines.size) } + @Test def loadFromResource() = { + val res = Source.fromResource("rootdoc.txt") + assertTrue("No classpath resource found", res.getLines().size > 5) + } @Test def canCustomizeReporting() = { class CapitalReporting(is: InputStream) extends BufferedSource(is) { override def report(pos: Int, msg: String, out: PrintStream): Unit = { -- cgit v1.2.3