14

I need to write a content to file in a single statement something like FileUtils.writeStringToFile.

Is there any alternative to it since it is deprecated?

1
  • 1
    Going by the documentation, the versions of writeStringToFile where you specify an encoding are not deprecated.
    – TiiJ7
    Commented Jan 2, 2019 at 9:12

5 Answers 5

14

By going through this documentation, It states that:

Deprecated. 2.5 use writeStringToFile(File, String, Charset) instead
Writes a String to a file creating the file if it does not exist using the default encoding for the VM.

You can follow this example:

final File file = new File(getTestDirectory(), "file_name.txt");
FileUtils.writeStringToFile(file, "content", "ISO-8859-1");

You can pass (String) null in your argument if you don't want to pass the encoding.

For more information, you can go through the link: Usage link

6

Use this one

File file = ...
String data = ...

try{
    FileUtils.writeStringToFile(file, data, Charset.defaultCharset());
}catch(IOException e){
    e.printStackTrace();
}
2

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) {
    e.printStackTrace();
}
0
1

The fix is to add Charset.defaultCharset() as the 3rd argument.

E.g. change from

writeStringToFile(file, data)

to

writeStringToFile(file, data, Charset.defaultCharset())

Source:

The documentation says:

Deprecated. 2.5 use writeStringToFile(File, String, Charset) instead

The source code for the deprecated function is:

    @Deprecated
    public static void writeStringToFile(final File file, final String data) throws IOException {
        writeStringToFile(file, data, Charset.defaultCharset(), false);
    }
-1

Have a look From your question I think you are searching option for FileUtils.writeStringToFile.
This link will provide the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.