java - 在java中的目录路径中添加单个正斜杠或双反斜杠
问题描述
我正在使用 JFileChooser 在我的项目中获取目录路径。它运行良好,但有一个小问题。假设这是目录结构:
->Home
->Documents
->Java
这是代码:
JFileChooser fileChooser=new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int userSelection=fileChooser.showSaveDialog(this);
if(userSelection==JFileChooser.APPROVE_OPTION){
try{File fileTosave=fileChooser.getSelectedFile();
File newFile=new File(fileTosave.getAbsolutePath()+"satish.txt");
System.out.println(newFile);
this.dispose();}
catch(Exception e){}
}
如果当前我在 java 文件夹中,它会给我Home/Documents/Java
Windows 中的路径(或 Home:\Documents\Java)。我想要的是它应该返回包含单正斜杠或双正斜杠(根据平台)的路径,使其看起来像Home/Documents/Java/
. 我想这样做是因为稍后我必须在此路径中附加一个文件名,以便文件路径变为Home/Documents/java/file.txt
.
关于如何做到这一点的任何想法?
我不想手动添加斜线,因为那样我还必须牢记平台。
谢谢!
解决方案
利用java.io.File.pathSeparator
/**
* The system-dependent path-separator character, represented as a string
* for convenience. This string contains a single character, namely
* <code>{@link #pathSeparatorChar}</code>.
*/
public static final String pathSeparator = "" + pathSeparatorChar;
您的代码应如下所示
JFileChooser fileChooser=new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int userSelection=fileChooser.showSaveDialog(this);
if(userSelection==JFileChooser.APPROVE_OPTION){
try{File fileTosave=fileChooser.getSelectedFile();
File newFile=new File(fileTosave.getParent() + File.separator +"satish.txt");
System.out.println(newFile);
this.dispose();}
catch(Exception e){}
}
推荐阅读
- python - 如何在 django 查询语句中通过外键和自然键显示来自不同表的字段
- javascript - 创建一个可访问的列表,其中每个 li 元素都有一些复杂的内容
- python - 从列表创建数据框
- selenium - I heard from an acquaintance that it is possible to programmatically cut Google's reCapcha so that it doesn't show image verification, is this true?
- django - 如何为 Django App 授权令牌流程创建流程
- swift - Swift:如何将另一个框架包含到您的框架中
- reactjs - TypeError:validateOptions 不是函数
- yaml - 将来自多个 SNS 主题的消息发送到单个 Amazon SQS
- stata - 当我在双向分散的 ylabel() 选项中包含破折号时出错
- javascript - 如何在 PHP 中的 MVC 上使用 AJAX