Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static String readStringFromFile(String fileName, boolean addEnterLindEnd) {
        StringBuilder result = new StringBuilder();
        FileInputStream fip = null;
        InputStreamReader inputReader = null;
        BufferedReader bufReader = null;
        try {
            File file = new File(fileName);
            if (file.exists() && file.isFile()) {
                fip = new FileInputStream(file);
                inputReader = new InputStreamReader(fip);
                bufReader = new BufferedReader(inputReader);
                String line = "";
                while ((line = bufReader.readLine()) != null) {
                    if (addEnterLindEnd) {
                        result.append(line + "\n");
                    } else {
                        result.append(line);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bufReader) {
                    bufReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != inputReader) {
                    inputReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != fip) {
                    fip.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result.toString();
    }
}