Apache FileUtils

To read a file as String, readFileToString(File file) method is used, below is an example

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class FileUtilsSample {

    @SuppressWarnings("CallToThreadDumpStack")
    public static void main(String[] args) {
        // Creating a file object 
        File file = new File("F:\\MyProjects\\sample.txt");
        try {
            // Reading the content of sample.txt as string
            String content = FileUtils.readFileToString(file);
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Now reading the a file line by line

try {
            // Reading the content of sample.txt line by line
            List<String> contents = FileUtils.readLines(file);
            
            //Total numbers of line present in sample.txt
            System.out.println("Lines = "+contents.size());

            // Iterating to print each line
            for (String line : contents) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
}

Now to write something into file we will use the method writeStringToFile(File file, String data), below is the example

public class FileUtilsSample {

    @SuppressWarnings("CallToThreadDumpStack")
    public static void main(String[] args) {
        try {
            // Creating a file object 
            File file = new File("F:\\MyProjects\\sample.txt");

            String data = "Debraj Mallick";

            // To write into the file, we have to pass
            // two parameters i.e. the file and the data
            // to be written (Previous content will be lost)
            FileUtils.writeStringToFile(file, data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Now to get the size of directory

long size = FileUtils.sizeOfDirectory(new File("C:/Windows"));
System.out.println("Size is : " + size + " bytes");
System.out.println("Size is : " + size / (1024 * 1024) + " mb");
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: