Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java windows环境中的文件路径问题_Java_Filepath - Fatal编程技术网

Java windows环境中的文件路径问题

Java windows环境中的文件路径问题,java,filepath,Java,Filepath,我有以下代码行: "%s/ramp_adapter/user_%d/ramp_file_receipt/%d".format(new java.io.File(".").getAbsolutePath().replace("/.",""), endpointId, fileId) 如果我在窗口中打印这一行,我会得到错误的文件路径: E:\git\project\codeAdapters\rampAdapter\./ramp_adapter/user_1001/ramp_file_receipt

我有以下代码行:

"%s/ramp_adapter/user_%d/ramp_file_receipt/%d".format(new java.io.File(".").getAbsolutePath().replace("/.",""), endpointId, fileId)
如果我在窗口中打印这一行,我会得到错误的文件路径:

E:\git\project\codeAdapters\rampAdapter\./ramp_adapter/user_1001/ramp_file_receipt/3
在unix中,文件路径是正确的

我知道我需要使它与windows兼容,所以我尝试使用,但这并没有解决问题


路径在所有环境中都应该正确。

当前工作目录
取决于应用程序的启动方式。你可以用

System.getProperty("user.dir")
而不是获得绝对路径

它可能会出现同样的问题:在Windows下单击会有问题

解决方案/解决方法可能是在Windows下创建批处理文件

我倾向于在用户的主文件夹中使用依赖于应用程序的目录。使用前一个期间隐藏时:

File myAppDir = new File(System.getProperty("user.home") + "/.myappname";
myAppDir.mkdir();
1) 使用System.getProperty(“file.separator”)获取当前OS文件 分离器。 2) 新的java.io.File(“.”).getAbsolutePath()将在linux中返回linux路径(/etc/uus/),在Windows中返回Windows路径(例如:C:\xpto\sdfs)

您需要按照自己的意愿进行标准化。

替换

"%s/ramp_adapter/user_%d/ramp_file_receipt/%d"

替换

getAbsolutePath().replace("/.","")


使用
File.getCanonicalFile()
规范生成的字符串。它将转换为右分隔符,并删除路径段

String s = "E:\\git\\project\\codeAdapters\\rampAdapter\\./ramp_adapter/user_1001/ramp_file_receipt/3";
File f = new File(s).getCanonicalFile();
assertEquals("E:\\git\\project\\codeAdapters\\rampAdapter\\ramp_adapter\\user_1001\\ramp_file_receipt\\3", f.toString());

unix中的
E:
是什么?这看起来是错误的。Windows反斜杠和unix使用正斜杠。@SkinnyJ-我没有查看unix系统,但在那里它运行良好。我在问题中假设并保留的位置在查看您的评论后似乎是错误的,因此我将其删除。您是否尝试使用
java.nio.file.Paths.get(String first,String…more)
构建路径而不是替换字符串?您将根据运行时获得正确的驱动器根目录和路径分隔符。您的端点错误
/ramp\u adapter/user\u 1001
。。。是否要持久化
/
部分?
文件
具有附加路径的构造函数,因此不必进行字符串连接。“因为那样做是件坏事。”扎普说得好;我想先打电话给mkdir(s)。也许现在我应该使用
Path,Paths.get(…),Files
。我可以想象使用这种分隔符处理不同环境的完美效果。引用
File.separatorChar
-“依赖于系统的默认名称分隔符。此字段初始化为包含系统属性File.separator值的第一个字符。在UNIX系统上,此字段的值为“/”;在Microsoft Windows系统上,此字段的值为“\\”。瞧!!虽然我的答案在功能上是正确的,但我建议使用
getCanonicalFile()
,重新编写代码以符合wero的答案/建议,因为这是一个更优雅的选择。我目前是他答案的唯一投票人。
getAbsolutePath().replace(File.separator + ".", "")
String s = "E:\\git\\project\\codeAdapters\\rampAdapter\\./ramp_adapter/user_1001/ramp_file_receipt/3";
File f = new File(s).getCanonicalFile();
assertEquals("E:\\git\\project\\codeAdapters\\rampAdapter\\ramp_adapter\\user_1001\\ramp_file_receipt\\3", f.toString());