开发者

How to get proper path in Java using JFileChooser as per the Operating system

In my Java application I need to select a path using JFileChooser. The code that I have written is as follows:

jfChooser = new JFileChooser();

jfChooser.setCurrentDirectory(new java.io.File("."));

jfChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (jfChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
System.out.println("getCurrentDirectory(): "+  jfChooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "+  jfChooser.getSelectedFile());
tfPath.setText(jfChooser.getSelectedFile().getAbsolutePath()); // the selected path set to textfield which is lated get by the program
}
else {
System.out.println("No Selection ");
}

I am getting the path properly.For example, here I am getti开发者_开发技巧ng the path (In Windows os)

String choosedPath=tfPath.getText().trimm();

Now actually I want to create a another directory on a given path (i.e. inside newfolder directory) programatically.

For that I have new directory name "newdir" so the string passed to File constructor for creating this directory is as follows:

File createFolder = new File("choosedPath"+"\\"+"newdir");

Now the problem is that my application may run on windows or may run on Linux so according to that the filepath seperator varies (i.e. '/' for windows and '\' for linux)

How do I Overcome this problem so that I will get propper slashes in path according to OS?


new File(choosedPath, "newDir");

Platform dependent file separator gonna be choose automatically.

You can too use File.separator to get platform dependent separator to construct the string but you going to end with more code than first solution.


Use File.separator instead of / or \.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜