Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/* 
 * Copyright (C) 2010 Giesecke & Devrient GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class Main {
    /**
     * For Fileoperations
     * Position in the file, which is written
     */
    private static long writeStreamPosition = 0L;
    /**
     * For Fileoperations
     * FileOutputStream-object to leave the stream open during multiple write-operations
     */
    private static FileOutputStream fos = null;

    /**
     * This method handels the write operations for a specified file.
     * 
     * @param file the file to which the data should be written.
     * @param data the data,which should be written to a specified file.
     * @param writeCompleted a flag which indicates, if writing to a file is complete, or
     *            if there data left, which should be append to the end of the
     *            file.
     */
    public static void writeFile(File file, byte[] data, boolean writeCompleted) {
        // Writing the encrypted data with header
        try {

            if (fos == null)
                fos = new FileOutputStream(file);

            FileChannel fileChannel = fos.getChannel();

            if (writeStreamPosition != 0L)
                fileChannel.position(writeStreamPosition);

            fos.write(data);
            fos.flush();

            writeStreamPosition = fileChannel.position();

            // reset flags, if file-operation is completed
            if (writeCompleted) {
                fileChannel.close();
                fos.close();
                fos = null;
                writeStreamPosition = 0L;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }
}