diff options
author | Adriaan Moors <adriaan.moors@typesafe.com> | 2015-07-07 11:51:11 -0700 |
---|---|---|
committer | Adriaan Moors <adriaan.moors@typesafe.com> | 2015-07-07 11:51:11 -0700 |
commit | b92c3aff1ab8c76c4816bd7b1a82a0f87d787837 (patch) | |
tree | ec7620b4bb7ebac43968f54135ee770ce064fe85 | |
parent | a6261efcc0b60589e912524402ca74d7608e45a3 (diff) | |
parent | 82fd8bc677abeece738fb281f53439661254d981 (diff) | |
download | scala-b92c3aff1ab8c76c4816bd7b1a82a0f87d787837.tar.gz scala-b92c3aff1ab8c76c4816bd7b1a82a0f87d787837.tar.bz2 scala-b92c3aff1ab8c76c4816bd7b1a82a0f87d787837.zip |
Merge pull request #4561 from jdevelop/io-source-fromclasspath-2.12
SI-7514 Introduce Source.fromResource(...) method
-rw-r--r-- | src/library/scala/io/Source.scala | 10 | ||||
-rw-r--r-- | test/junit/scala/io/SourceTest.scala | 4 |
2 files changed, 14 insertions, 0 deletions
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 = { |