Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    public static String readFile(final String path, final String fileName) {
        final File file = new File(path, fileName);
        final StringBuilder builder = new StringBuilder();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                builder.append(line);
                builder.append('\n');
            }
        } catch (final Exception ex) {
            ex.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (final IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        return builder.toString();
    }

    /**
     * Convert InputStream to String
     * 
     * @param is
     * @return string
     * @throws Exception
     */
    public static String toString(final InputStream is) throws Exception {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            final byte[] buffer = new byte[4096];
            for (int b = is.read(buffer); b >= 0; b = is.read(buffer)) {
                out.write(buffer, 0, b);
            }
            return new String(out.toByteArray());
        } catch (final Exception e) {
            throw e;
        }
    }
}