Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 935
rocky Avatar asked Jan 02 '19 09:01

rocky


3 Answers

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

like image 145
Rajendra arora Avatar answered Nov 03 '22 19:11

Rajendra arora


Use this one

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

try{
    FileUtils.writeStringToFile(file, data, Charset.defaultCharset());
}catch(IOException e){
    e.printStackTrace();
}
like image 39
NM Naufaldo Avatar answered Nov 03 '22 17:11

NM Naufaldo


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();
}
like image 23
Kami Kaze Avatar answered Nov 03 '22 18:11

Kami Kaze