How to construct a file path in Java
Here’s two “how to” Java examples to construct a file path :
- Check the operating system and create the file separator manually. (Not recommend)
- Let’s Java do all the job ~ File.separator. (Best Practice)
File.separator is always recommended, because it will check your OS and display the correct file separator automatically, For example,
- Windows – Return “\”
- *nix – Return “/”
Manual file separator example
A classic way to construct a file path manually, which is not recommended.
package com.mkyong.file; import java.io.File; import java.io.IOException; public class FilePathExample { public static void main( String[] args ) { try { String filename = "testing.txt"; String finalfile = ""; String workingDir = System.getProperty("user.dir"); String your_os = System.getProperty("os.name").toLowerCase(); if(your_os.indexOf("win") >= 0){ finalfile = workingDir + "\\" + filename; }else if(your_os.indexOf( "nix") >=0 || your_os.indexOf( "nux") >=0){ finalfile = workingDir + "/" + filename; }else{ finalfile = workingDir + "{others}" + filename; } System.out.println("Final filepath : " + finalfile); File file = new File(finalfile); if (file.createNewFile()){ System.out.println("Done"); }else{ System.out.println("File already exists!"); } } catch (IOException e) { e.printStackTrace(); } } }
File.separator example
A proper way is use the File.separator, see the different, just one line code can do all the checking above.
package com.mkyong.file; import java.io.File; import java.io.IOException; public class FilePathExample { public static void main( String[] args ) { try { String filename = "testing.txt"; String finalfile = ""; String workingDir = System.getProperty("user.dir"); finalfile = workingDir + File.separator + filename; System.out.println("Final filepath : " + finalfile); File file = new File(finalfile); if (file.createNewFile()){ System.out.println("Done"); }else{ System.out.println("File already exists!"); } } catch (IOException e) { e.printStackTrace(); } } }
Reference
- http://java.sun.com/javase/6/docs/api/java/io/File.html
- http://www.mkyong.com/java/how-to-get-the-current-working-directory-in-java/
- http://lopica.sourceforge.net/os.html
- http://www.mkyong.com/java/how-to-detect-os-in-java-systemgetpropertyosname/
[...] Construct file path [...]
This can be even more simple
String filename = “testing.txt”;
String workingDir = System.getProperty(“user.dir”);
File file = new File(workingDir, filename);
hi kdt, thanks for your tip ~
[...] How to construct a file path in Java | J2EE Web Development Tutorials [...]