Showing posts with label java write files. Show all posts
Showing posts with label java write files. Show all posts

Friday, December 5, 2014

Reading and Writing Files in Java

Here is code to read and write from a file in Java. You will have to change the output path and package appropriately.

package com.mycompany.app.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class FileHelper {
    
    public static void main(String[] args) {
        try {
            System.out.println("START");
            String outputPath = "/Users/Scott/workspace/myrepo/my-app/output/text.txt";
            FileHelper fileHelper = new FileHelper();
            fileHelper.write(new File(outputPath), "Hello World!
My First HTML Page!");
            String string = fileHelper.read(new File(outputPath));
            System.out.println("From FILE:"+string);
            System.out.println("FINISH");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public String read(File inputFile) throws Exception {
        // Initialization
        String string = "";
        String line;
        
        // Read from file
        FileReader fr = new FileReader(inputFile);
        BufferedReader br = new BufferedReader(fr);
        while ((line = br.readLine()) != null) {
            string = string + line;
        }
        br.close();
        fr.close();
        
        return string;
    }

    public void write(File outputFile, String string) throws Exception {
        // Initialization
        if (!outputFile.exists()) {
            outputFile.createNewFile();
        }

        // Write to file
        FileWriter fw = new FileWriter(outputFile);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(string);
        bw.close();
        fw.close();

    }
}


This post was reposted from http://scottizu.wordpress.com/2013/08/19/reading-and-writing-files-in-java/, originally written on August 19th, 2013.