- เชคระบบปฏิบัติการและสร้างตัวคั่น(\ หรือ /)กำหนดเอง. (ไม่แนะนำ)
- ให้ Java เป็นตัวจัดการทั้งหมดโดยใช้ File.separator. (แนะนำ)
- Windows ใช้ "\"
- *nix – ใช้ "/"
package demo.file; import java.io.File; import java.io.IOException; /** * @author nopphanan7 * */ public class FilePathExample { /** * @param args */ 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(); } } }ผลลัพธ์ที่ได้คือ
Final filepath : D:\workspace\testjava\testing.txt Done
แบบใช้ File.separator ดังตัวอย่างต่อไปนี้.
package demo.file; import java.io.File; import java.io.IOException; /** * @author nopphanan7 * */ public class FilePathExample { /** * @param args */ 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(); } } }ผลลัพธ์ที่ได้คือ
Final filepath : D:\workspace\testjava\testing.txt File already exists!
0 comments:
Post a Comment