Java 建立和寫入檔案
建立檔案
要在 Java 中建立檔案,您可以使用 createNewFile()
方法。此方法返回一個布林值:如果檔案成功建立,則返回 true
;如果檔案已存在,則返回 false
。請注意,該方法被封裝在一個 try...catch
塊中。這是必需的,因為它在發生錯誤時(如果檔案因某種原因無法建立)會丟擲 IOException
。
示例
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
輸出將是:
檔案已建立:filename.txt
要在特定目錄中建立檔案(需要許可權),請指定檔案的路徑,並使用雙反斜槓來轉義“\
”字元(對於 Windows)。在 Mac 和 Linux 上,您可以直接寫入路徑,例如:/Users/name/filename.txt
寫入檔案
在以下示例中,我們使用 FileWriter
類及其 write()
方法將一些文字寫入我們在上面示例中建立的檔案。請注意,當您完成檔案寫入後,應該使用 close()
方法關閉檔案。
示例
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
輸出將是:
成功寫入檔案。
要讀取上述檔案,請轉到 Java 讀取檔案 章。