What is the alternative to deprecated the FileUtils.writeStringToFile method?

Posted in :


在使用 FileUtils.writeStringToFile 時, 顯示 deprecated:

解法, 多增加一個字串內容編碼參數即可.

Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:

static void writeStringToFile(File file, String data, Charset charset) 

which allows you to write text to a file in one method call:

FileUtils.writeStringToFile(new File("test.txt"), "Hello File", Charset.forName("UTF-8"));

You might also want to consider specifying the encoding for the file as well.


You can use Files from the Java standard library aswell – unless you need to use apache commons.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

// to write to your file use

try {
    // To overwrite
    Files.write(Paths.get("Your\\path"), "YourString".getBytes(), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
    // To append to the file
    Files.write(Paths.get("Your\\path"), "YourString".getBytes(), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
} catch (IOException e) {



發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *