簡體   English   中英

使用java.io.File在文件系統上創建文件

[英]Creating file on filesystem with java.io.File

我正在嘗試使用java.io.File在我的文件系統上創建一個空的.properties文件。

我的代碼是:

File newFile = new File(new File(".").getAbsolutePath() + "folder\\" + newFileName.getText() + ".properties");

if (newFile.createNewFile()){
    //do sth...
}

它說不可能找到指定的路徑。 打印文件的構造函數的參數,可以正確顯示絕對路徑。

怎么了?

我覺得 ”。” 操作員可能會導致錯誤,不確定您要在此做什么,可能是誤解了您的意圖,請改用以下方法:

File newFile = new File(new File("folder\\").getAbsolutePath() + ".properties"); 
  1. 您可以使用new File("folder", newFileName.getText() + ".properties")來創建相對於當前工作目錄的folder目錄中指定文件的文件引用
  2. 您應該在調用createNewFile之前確保該目錄存在,因為它不會為您這樣做

例如...

File newFile = new File("folder", newFileName.getText() + ".properties");
File parentFile = newFile.getParentFile();
if (parentFile.exists() || parentFile.mkdirs()) {
    if (!newFile.exists()) {
        if (newFile.createNewFile()){
            //do sth...
        } else {
            throw new IOException("Could not create " + newFile + ", you may not have write permissions or the file is opened by another process");
        }
    }
} else {
    throw new IOException("Could not create directory " + parentFile + ", you may not have write permissions");
}

平常我錯過了new File(".").getAbsolutePath()返回帶有的項目的絕對路徑. 最后我的folder應該叫做.folder 下次我會檢查兩次。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM