简体   繁体   English

如何给出文件的相对路径?

[英]How to give relative path for a file?

When i give the absolute path of twitter.R file it runs correctly. 当我给出twitter.R文件的绝对路径时,它将正确运行。 like this: 像这样:

c.eval("source(\"C:\\\\Users\\\\Ruttab\\\\workspace\\\\RserveConnect\\\\src\\\\main\\\\resources\\\\Script\\\\twitter.R\")");

When i give the relative path it doesnt run and gives me an error. 当我给出相对路径时,它不会运行并给我一个错误。 like this: 像这样:

c.eval("source(\"/src/main/resources/Resources/Rscripts/twitter.R\")");

How to give relative path for the file twitter.R 如何给出文件twitter.R的相对路径

This is my project hieachy: 这是我的项目hieachy:

在此处输入图片说明

String relative = new File(base).toURI().relativize(new 
File(path).toURI()).getPath();

add an example: 添加一个示例:

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"

import java.nio.file.Path; 导入java.nio.file.Path; import java.nio.file.Paths; 导入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);
    }

}

You can declare Path with relative paths, but that won't solve your issue. 您可以使用相对路径声明Path ,但这不会解决您的问题。 You cannot expect your java process to know the root directory of your source files just like that. 您不能期望Java进程那样知道源文件的根目录。

Your project is likely to be built and packaged as a jar (or a war) and the relative path to your resources may change. 您的项目可能会以罐子(或战争)的形式构建和打包,并且通往资源的相对路径可能会发生变化。

The proper solution to your issue is to get it from the classpath, as explained in this answer 正确的解决方案是从类路径中获取它,如本答案所述

Short version : InputStream input = this.getClass().getResourceAsStream("/Resources/Rscripts/twitter.R"); 简短版本: InputStream input = this.getClass().getResourceAsStream("/Resources/Rscripts/twitter.R");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM