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 of org.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 of org.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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button