Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

/*
 * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2006.
 *
 * Licensed under the Aduna BSD-style license.
 */
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

public class Main {

    /**
     * Writes all characters from a <tt>Reader</tt> to a file using the default
     * character encoding.
     *
     * @param reader The <tt>Reader</tt> containing the data to write to the
     * file.
     * @param file The file to write the data to.
     * @return The total number of characters written.
     * @throws IOException If an I/O error occured while trying to write the
     * data to the file.
     * @see java.io.FileWriter
     */
    public static final long writeToFile(Reader reader, File file) throws IOException {
        FileWriter writer = new FileWriter(file);

        try {
            return transfer(reader, writer);
        } finally {
            writer.close();
        }
    }

    /**
     * Transfers all characters that can be read from <tt>in</tt> to
     * <tt>out</tt>.
     *
     * @param in The Reader to read characters from.
     * @param out The Writer to write characters to.
     * @return The total number of characters transfered.
     */
    public static final long transfer(Reader in, Writer out) throws IOException {
        long totalChars = 0;
        int charsInBuf = 0;
        char[] buf = new char[4096];

        while ((charsInBuf = in.read(buf)) != -1) {
            out.write(buf, 0, charsInBuf);
            totalChars += charsInBuf;
        }

        return totalChars;
    }
}