将Windows风格的路径转换为Unix路径 [英] Convert Windows-style path into Unix path

查看:362
本文介绍了将Windows风格的路径转换为Unix路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个表示路径的字符串,并将其转换为绝对的Unix风格路径。这个字符串可以是Windows或Unix样式,因为它是调用 MainClass.class.getClassLoader()。getResource()。getPath()的结果,根据您的系统返回不同的样式路径。

I want to take a string that represents a path and convert it to an absolute Unix-style path. This string could be in either Windows or Unix styles, as it's the result of a call to MainClass.class.getClassLoader().getResource("").getPath(), which returns different style paths depending on your system.

(我正在为我正在编写的游戏执行此操作,其中一部分为用户提供简单的bash -ishshell,我希望用户能够读取文件。假文件系统作为普通目录树存储在我项目的子目录中。这个文件系统将使用Unix风格的路径,我想成为能够将输入的路径与前面提到的字符串连接起来(进行一些小的编辑以使其进入正确的目录)所以我可以找到文件的内容。)

(I'm doing this for a game I'm writing, a portion of which gives the user a simple "bash-ish" shell, and I want the user to be able to read files. The fake filesystem is stored as a normal directory tree in a subdirectory of my project. This filesystem is going to use Unix-style paths, and I want to be able to concatenate inputted paths with the aforementioned string (with some minor edits to get it into the right directory) so I can find the contents of the files.)

任何想法我该怎么做呢?我尝试了很多东西,但我似乎无法让它在我朋友的Windows 7系统上正常工作。

Any ideas how I might go about doing this? I've tried a number of things, but I can't seem to get it to work properly on my friend's Windows 7 system.

目前我只是使用一个简单的东西来检查字符串是否以C:\或类似的东西开头,然后用斜杠替换反斜杠但是,这并不是一个很好的方法来解决这个问题,而且我确信其他人之前也遇到过不同路径风格的问题。这当然是一个非常临时的解决方案。

At the moment I'm just using a simple thing that checks to see if the string starts with "C: \" or something similar and then replaces backslashes with slashes, but there's no way that that can be a good way to go about this, and I'm sure other people have faced the problem of different path styles before. It's certainly a very temporary solution.

推荐答案

一般情况下,我在任何使用'/'的操作系统上都没遇到过问题分隔符。

In general, I never had problems on any operating system with using a '/' as separator.

 new File("/a/b/c.txt");

至少适用于Unix,Windows和iSeries。

works at least on Unix, Windows and iSeries.

如果你想要正确,有一个常量'File.separator',它保存操作系统分隔符。

If you want to be correct, there's a constant 'File.separator', that holds the operating systems separator.

如果你想替换反斜杠' \'在一个字符串中,记住它是一个特殊的转义符:

If you want to replace the backslash '\' in a string, remember that it is a special escape character:

String newString = str.replace("\\","/");

编辑

并记住,String是不可变的。

and remember, String is immutable.

 str.replace("\\","/");

不会更改字符串,只返回带有替换字符的新字符串。

will not change the string, only return a new string with the replaced characters.

这篇关于将Windows风格的路径转换为Unix路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆