2017-05-31 67 views
0

當我給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:

enter image description here

+0

相對的是什麼?該過程如何知道從哪裏開始解析相對路徑?你知道你的文件是打包在一個罐子裏嗎?你應該把它聲明爲'資源' –

+0

@JeremyGrand我該如何聲明它是一個資源? –

+0

參考問題https://stackoverflow.com/questions/2639943/accessing-jar-resources –

回答

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" 
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); 
    } 

} 
+0

嗨jdpom,請[編輯]來糾正你的前兩行(需要縮進4個空格)的格式。如果您包含一些評論或代碼所做的描述,這也很有幫助。謝謝! – whrrgarbl

0

你可以用相對路徑聲明Path,但不會解決您的問題。你不能指望你的java進程知道你的源文件的根目錄。

您的項目很可能會構建並打包爲jar(或戰爭),並且您的資源的相對路徑可能會更改。

你的問題的妥善解決是從classpath得到它,因爲在這個answer

短版解釋:InputStream input = this.getClass().getResourceAsStream("/Resources/Rscripts/twitter.R");

+0

這是打印輸入時得到的輸出= [email protected]。這不是錯的嗎? –

+0

您需要解碼'InputStream'的內容。你可以用'InputStreamReader'封裝流。 –

+0

這不起作用。我的腳本的內容運行。它不給我相對路徑 –