我有一个火花流 https://spark.apache.org/streaming/使用 Maven(作为 jar)构建并使用spark-submit
脚本。应用程序项目布局遵循标准目录布局:
myApp
src
main
scala
com.mycompany.package
MyApp.scala
DoSomething.scala
...
resources
aPerlScript.pl
...
test
scala
com.mycompany.package
MyAppTest.scala
...
target
...
pom.xml
In the DoSomething.scala
对象我有一个方法(我们称之为doSomething()
) 尝试执行 Perl 脚本 --aPerlScript.pl
(来自resources
文件夹)——使用scala.sys.process.Process
并向脚本传递两个参数(第一个参数是用作输入的二进制文件的绝对路径,第二个参数是生成的输出文件的路径/名称)。我然后打电话DoSomething.doSomething()
.
问题是我无法访问脚本,不能使用绝对路径、相对路径、getClass.getClassLoader.getResource、getClass.getResource,我已在我的资源文件夹中指定了资源文件夹pom.xml
。我的尝试都没有成功。我不知道如何找到我放在 src/main/resources 中的东西。
我将不胜感激任何帮助。
附注:
- 我使用外部进程而不是 Spark 管道,因为在工作流程的这一步,我必须处理二进制文件作为输入和输出。
- 我正在使用 Spark-streaming 1.1.0、Scala 2.10.4 和 Java 7。我从 Eclipse (Kepler) 中使用“Maven install”构建 jar
- 当我使用
getClass.getClassLoader.getResource
访问资源的“标准”方法我发现实际的类路径是spark-submit
脚本就是其中之一。
有几种解决方案。最简单的是使用 Scala 的流程基础设施:
import scala.sys.process._
object RunScript {
val arg = "some argument"
val stream = RunScript.getClass.getClassLoader.getResourceAsStream("aPerlScript.pl")
val ret: Int = (s"/usr/bin/perl - $arg" #< stream).!
}
在这种情况下,ret
是进程的返回代码,进程的任何输出都定向到stdout
.
第二种(更长)的解决方案是复制文件aPerlScript.pl
从 jar 文件到某个临时位置并从那里执行它。此代码片段应该包含您需要的大部分内容。
object RunScript {
// Set up copy destination from the Java temporary directory. This is /tmp on Linux
val destDir = System.getProperty("java.io.tmpdir") + "/"
// Get a stream to the script in the resources dir
val source = Channels.newChannel(RunScript.getClass.getClassLoader.getResourceAsStream("aPerlScript.pl"))
val fileOut = new File(destDir, "aPerlScript.pl")
val dest = new FileOutputStream(fileOut)
// Copy file to temporary directory
dest.getChannel.transferFrom(source, 0, Long.MaxValue)
source.close()
dest.close()
}
// Schedule the file for deletion for when the JVM quits
sys.addShutdownHook {
new File(destDir, "aPerlScript.pl").delete
}
// Now you can execute the script.
这种方法允许您将本机库捆绑在 JAR 文件中。将它们复制出来可以在运行时加载库,以应对您计划的任何 JNI 恶作剧。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)