get Source Code From File - Java File Path IO

Java examples for File Path IO:Text File

Description

get Source Code From File

Demo Code


//package com.java2s;
import java.io.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        File file = new File("Main.java");
        System.out.println(getSourceCodeFromFile(file));
    }/*w w  w  . j  av a 2  s.c o  m*/

    public static String getSourceCodeFromFile(File file) {
        String sourceCode = "";
        if (file == null) {
            return sourceCode;
        }
        try {
            Reader reader = new FileReader(file);
            sourceCode = getString(reader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sourceCode;
    }

    private static String getString(Reader reader) throws IOException {
        String text = "";
        BufferedReader bufferedReader = new BufferedReader(reader);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            text += line + "\n";
        }
        return text;
    }
}

Related Tutorials