Java 分割了路径..?
这是字符串输入:
"C:\jdk1.6.0\bin\program1.java"
我需要输出为:
Path-->C:\jdk1.6.0\bin\
file--->program1.java
extension--->.java
注意“\”字符。我很容易得到“/”的输出。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
File 类为您提供所需的一切:
编辑:感谢 Dave 指出,如果 File.getName 不包含“.”,则 String.lastIndexOf 将返回 -1。
The File class gives you everything you need:
EDIT: Thanks Dave for noting that String.lastIndexOf will return -1 if File.getName does not contain '.'.
考虑使用现有的解决方案,而不是自行推出并引入更多需要测试的代码。 Apache Commons IO 中的 FilenameUtils 就是一个示例:
http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FilenameUtils.html
Consider using an existing solution instead of rolling your own and introducing more code that needs to be tested. FilenameUtils from Apache Commons IO is one example:
http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FilenameUtils.html
由于 Java 的
File
类不支持探测扩展,我建议您创建一个提供此功能的File
子类:现在只需将您的 File 版本替换为 Java 的版本,然后与库尔特的答案相结合,可以为您提供所需的一切。
请注意,使用子类是理想的选择,因为如果您想要更改行为(由于不同的操作系统使用不同的扩展分隔符标记),您只需要更新一个方法,整个应用程序就可以继续工作。 (或者如果您需要修复错误,例如尝试执行
str.substring( -1 )
。)换句话说,如果您在多个位置提取文件扩展名< /em> 在你的代码库中,你犯了一个错误。
更进一步,如果您想完全抽象文件类型的知识(因为某些操作系统可能不使用
.
分隔符),您可以这样写:我认为这是一个更强大的解决方案。这将无缝地允许替换更高级的文件类型检测机制(分析文件内容以确定类型),而无需更改调用代码。示例:
如果用户将“myfile.png”保存为“myfile.txt”,则仍会处理该图像,因为高级版本(此处未显示)将查找在 (网络)世界。
Since Java's
File
class does not support probing for the extension, I suggest you create a subclass ofFile
that provides this ability:Now simply substitute your version of File for Java's version and, when combined with Kurt's answer, gives you everything you need.
Notice that using a subclass is ideal because if you wanted to change the behaviour (due to a different operating system using a different extension delimiter token), you need only update a single method and your entire application continues to work. (Or if you need to fix a bug, such as trying to execute
str.substring( -1 )
.)In other words, if you extract a file extension in more than one place in your code base, you have made a mistake.
Going further, if you wanted to completely abstract the knowledge of the file type (because some operating systems might not use the
.
separator), you could write:I would consider this a much more robust solution. This would seamlessly allow substituting a more advanced file type detection mechanism (analysis of file contents to determine the type), without having to change the calling code. Example:
If a user saved "myfile.png" as "myfile.txt", the image would still be processed because the advanced version (not shown here) would look for the "PNG" marker that starts every single PNG file in the (cyber) world.
您需要补偿 Path 中返回的双斜杠(如果它是通过编程生成的)。
You need to compensate for the double slashes returned in Path (if it has been programmatically generated).