使用 File file = new File(fileName) 檢查檔案是否存在,若不存在則呼叫 createNewFile()。執行時拋出 java.io.IOException: 系統找不到指定的路徑。
傳入的 fileName 為相對路徑,Java 以「當前工作目錄」為基準解析。若工作目錄非預期資料夾,會導致路徑不存在,無法建立檔案。
E:/test.txt。System.getProperty("user.dir") 取得工作目錄,再拼接相對路徑。file.getParentFile().mkdirs() 建立多層目錄。import java.io.*;
public class FileUtil {
public static void saveFile(String fileName, String content) throws IOException {
File file = new File(fileName);
// 確保父目錄存在
File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
if (!file.exists()) {
System.out.println("檔案不存在,建立中...");
file.createNewFile();
}
try (FileOutputStream fos = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw)) {
bw.write(content);
bw.newLine();
bw.flush();
System.out.println("寫入成功!");
}
}
public static void main(String[] args) throws IOException {
// 使用絕對路徑或動態路徑
String path = System.getProperty("user.dir") + "/data/test.txt";
saveFile(path, "測試內容");
}
}
createNewFile() 僅建立檔案,不建立目錄。/ 或 \\,建議統一用 /。IOException 讓呼叫端處理錯誤。