Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

import java.io.File;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
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 void writeStringAndClose(OutputStream destination, String data) throws IOException {
        try {
            writeString(destination, data, UTF8_ENCODING);
        } finally {
            destination.close();
        }
    }

    public static void writeString(File destination, String data) throws IOException {
        writeString(destination, data, UTF8_ENCODING);
    }

    public static void writeString(File destination, String data, String encoding) throws IOException {
        writeBytes(destination, data.getBytes(encoding));
    }

    public static void writeString(OutputStream destination, String data) throws IOException {
        writeString(destination, data, UTF8_ENCODING);
    }

    public static void writeString(OutputStream destination, String data, String encoding) throws IOException {
        writeBytes(destination, data.getBytes(encoding));
    }

    public static void writeBytes(File destination, byte[] data) throws IOException {
        saveToFile(new ByteArrayInputStream(data), destination);
    }

    public static void writeBytes(OutputStream destination, byte[] data) throws IOException {
        transfer(new ByteArrayInputStream(data), destination);
    }

    public static void saveToFile(InputStream in, File dst) throws FileNotFoundException, IOException {
        OutputStream out = new FileOutputStream(dst);
        try {
            transfer(in, out);
        } finally {
            out.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;
        }
    }
}