io
Set content to a file
In this example we shall show you how to set the content to a File. We will make use of the org.apache.commons.io.FileUtils
class, that provides file manipulation utilities. To set the content to a File one should perform the following steps:
- Create a new File by converting the pathname string of the file into an abstract pathname.
- Create a String to be written to the file.
- Use
writeStringToFile(File file, String data)
API method oforg.apache.commons.io.FileUtils
, that writes the String to the file creating the file if it does not exist using the default encoding for the VM. - Use
readFileToString(File file)
API method oforg.apache.commons.io.FileUtils
to read the contents of the file,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class SetContent { public static void main(String[] args) { try { // We take a reference to an actual file on disk File file = new File("test.txt"); // We set the string to be written to the file String data = "Javacodegeeks!!!"; // We write to the file with writeStringToFile Method FileUtils.writeStringToFile(file, data); // We test the result String content = FileUtils.readFileToString(file); System.out.println("Content : " + content); } catch (IOException e) { e.printStackTrace(); } } }
Output:
Content : Javacodegeeks!!!
This was an example of how to set the content to a File.