我想使用isDirectory()方法(java.io.File 類)。我創建了一個簡單的測驗代碼來嘗試這種方法,但是我總是收到“找不到符號”錯誤。
我的代碼:
import java.io.File;
public class MyUtils {
public static void main(String[] args) {
String path = "/this/is/not/a/valid/path";
boolean ValidPath = path.isDirectory();
System.out.println(ValidPath);
}
}
uj5u.com熱心網友回復:
因為你path是一個String物件。您可以File使用路徑實體化一個物件String:
boolean ValidPath = new File(path).isDirectory();
uj5u.com熱心網友回復:
發生這種情況是因為path是實體型別String,isDirectory而不是String類中可用的方法。要處理檔案或目錄,您必須使用適當的類。
您的代碼應如下所示:
import java.nio.file.Files;
import java.nio.file.Paths;
public class MyUtils {
public static void main(String[] args) {
String path = "/this/is/not/a/valid/path";
boolean isValidPath = Files.isDirectory(Paths.get(path));
System.out.println(isValidPath);
}
}
該ValidPath應改名isValidPath。
當你想檢查你的路徑的有效性時,你可以使用這樣的方法exists:
boolean isValidPath = Files.exists(Paths.get(path));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/351415.html
上一篇:如何在python中撰寫列印功能
下一篇:如何回傳指向線性串列中專案的指標
