当我给出twitter.R文件的绝对路径时,它正确运行。像这样:
c.eval("source(\"C:\\\\Users\\\\Ruttab\\\\workspace\\\\RserveConnect\\\\src\\\\main\\\\resources\\\\Script\\\\twitter.R\")");
当我给出相对路径时,它不会运行并给我一个错误。像这样:
c.eval("source(\"/src/main/resources/Resources/Rscripts/twitter.R\")");
如何为文件twitter.R提供相对路径
这是我的项目hieachy:
答案 0 :(得分:3)
String relative = new File(base).toURI().relativize(new
File(path).toURI()).getPath();
添加一个例子:
String path = "/var/caiyongji/tmp/abc.txt";
String base = "/var/caiyongji";
String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();
// relative == "tmp/abc.txt"
答案 1 :(得分:2)
import java.nio.file.Path; import java.nio.file.Paths;
public class Test {
public static void main(String[] args) {
Path pathAbsolute = Paths.get("/var/data/stuff/xyz.dat");
Path pathBase = Paths.get("/var/data");
Path pathRelative = pathBase.relativize(pathAbsolute);
System.out.println(pathRelative);
}
}
答案 2 :(得分:0)
您可以使用相对路径声明Path
,但这不会解决您的问题。您不能指望您的java进程知道源文件的根目录。
您的项目可能会被构建并打包为jar(或战争),并且资源的相对路径可能会发生变化。
问题的正确解决方法是从类路径中获取它,如answer中所述
简短版本:InputStream input = this.getClass().getResourceAsStream("/Resources/Rscripts/twitter.R");