ตัวอย่าง เช่น
File file = File("C:\\users\\nopphanan7\\newfile.txt");
System.out.println("Path : " + file.getAbsolutePath());
โดยมันจะคืนค่า path เต็มคือ : "Path : C:\\abcfolder\\textfile.txt".
โดยทั่วไปแล้วในการเรียกคืนค่า path นั้นเราต้องการ path จริงๆคือ "C:\\users\\nopphanan7\\" โดยที่ไม่มีชื่อไฟล์ติดมาด้วย หากเป็นเช่นนั้นแล้วแนะนำให้ใช้เมธอด substring() และ lastIndexOf() ครับเพื่อให้ได้ path ที่ต้องการจริงๆ :
File file = File("C:\\users\\nopphanan7\\newfile.txt");
String absolutePath = file.getAbsolutePath();
String filePath = absolutePath.substring(0,absolutePath.lastIndexOf(File.separator));
ตัวอย่าง
ต่อไปนี้คือตัวอย่างโดยการสร้างไฟล์ชั่วคราวและคืนค่า path ของไฟล์ครับ.
package demo.file;
import java.io.File;
import java.io.IOException;
public class AbsoluteFilePathExample {
/**
* @param args
*/
public static void main(String[] args) {
try {
File temp = File.createTempFile("i-am-a-temp-file", ".tmp");
String absolutePath = temp.getAbsolutePath();
System.out.println("File path : " + absolutePath);
String filePath = absolutePath.substring(0,absolutePath.lastIndexOf(File.separator));
System.out.println("File path : " + filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ผลลัพธ์ที่ได้คือ
File path : C:\Users\NOPPHA~1\AppData\Local\Temp\i-am-a-temp-file5548803754622769512.tmp File path : C:\Users\NOPPHA~1\AppData\Local\Tempตัวอย่างเพิ่มเติม ให้ใช้ getParent() ครับ
package demo.file;
import java.io.File;
import java.io.IOException;
public class AbsoluteFilePathExample {
/**
* @param args
*/
public static void main(String[] args) {
try {
File temp = File.createTempFile("i-am-a-temp-file", ".tmp");
String absolutePath = temp.getAbsolutePath();
System.out.println("File path : " + absolutePath);
String filePath = temp.getParent();
System.out.println("File path : " + filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
ผลลัพธ์ที่ได้คือ
File path : C:\Users\NOPPHA~1\AppData\Local\Temp\i-am-a-temp-file5875198742387051911.tmp File path : C:\Users\NOPPHA~1\AppData\Local\Temp
0 comments:
Post a Comment