Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

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

import java.io.OutputStream;

public class Main {
    public static final String UTF8_ENCODING = "utf-8";

    public static String readAsStringAndClose(InputStream source) throws IOException {
        try {
            return readAsString(source, UTF8_ENCODING);
        } finally {
            source.close();
        }
    }

    public static String readAsString(File source) throws IOException {
        return readAsString(source, UTF8_ENCODING);
    }

    public static String readAsString(File source, String encoding) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        loadFromFile(source, baos);
        byte[] bytes = baos.toByteArray();
        return new String(bytes, encoding);
    }

    public static String readAsString(InputStream source) throws IOException {
        return readAsString(source, UTF8_ENCODING);
    }

    public static String readAsString(InputStream source, String encoding) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        transfer(source, baos);
        byte[] bytes = baos.toByteArray();
        return new String(bytes, encoding);
    }

    public static void loadFromFile(File src, OutputStream out) throws FileNotFoundException, IOException {
        InputStream in = new FileInputStream(src);
        try {
            transfer(in, out);
        } finally {
            in.close();
        }
    }

    public static void transfer(InputStream in, OutputStream out) throws IOException {
        byte[] buf = new byte[1024 * 1024];
        int len;
        while ((len = in.read(buf)) > 0)
            out.write(buf, 0, len);
    }

    public static void transfer(InputStream in, OutputStream out, int maxBytes) throws IOException {
        byte[] buf = new byte[maxBytes];
        int done = 0;
        int len;
        while (done < maxBytes && (len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
            done += len;
        }
    }
}