Scala:在 sbt 中更改文件夹 [英] Scala: change folder inside sbt
问题描述
我有一个多模块的 sbt 项目,我想在我的项目的根文件夹中运行一个命令;因此我需要做 cd ../..
.
I have a multi-module sbt project and I want to run a command in the root folder of my project; hence I need to do cd ../..
.
我试过了
import sys.process._
"cd ../..".!
但我得到以下信息:
java.io.IOException: Cannot run program "cd": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at scala.sys.process.ProcessBuilderImpl$Simple.run(ProcessBuilderImpl.scala:69)
at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.run(ProcessBuilderImpl.scala:98)
at scala.sys.process.ProcessBuilderImpl$AbstractBuilder.$bang(ProcessBuilderImpl.scala:112)
推荐答案
cd
实际上并不是一个程序.它是一个 shell 内部的,它告诉 shell chdir
系统调用.Java 甚至没有使整个 jvm 更改其 cwd(当前工作目录)的功能(请参阅 在 Java 中更改当前工作目录?) -- 对于 Java 文件访问,有 user.dir
属性,但这只是 Java 函数看起来的一个变量在.
cd
is not actually a program. It's a shell-internal that tells the shell to the chdir
system call. Java doesn't even have a function to make the entire jvm to change its cwd (current working directory) (see Changing the current working directory in Java?) -- for Java file access, there is the user.dir
property, but that's just a variable that Java functions look at.
一个选项是执行 sh -c "..."
,在 fork 进程中改变目录,如下所示:
One option is executing sh -c "..."
, changing the directory within the forked process, like so:
import sys.process._
val cmd = "whatever you wanted to run"
s"sh -c 'cd ../..; $cmd'".!
但最好还是使用 http://www.scala-lang.org/files/archive/api/current/index.html#scala.sys.process.Process$ 工厂同时采用 命令
和一个 cwd
:
But better still would be to use the http://www.scala-lang.org/files/archive/api/current/index.html#scala.sys.process.Process$ factories that take both a command
and a cwd
:
scala.sys.process.Process("your command here", new java.io.File("/some/dir"))
要使用相对目录,您可能需要从 user.dir
和../.."创建 cwd 和/或执行类似 如何在java中定义相对路径
To use a relative dir, you might need to create the cwd from user.dir
and "../.." and/or do something like How to define a relative path in java
这篇关于Scala:在 sbt 中更改文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!