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.FileInputStream;
import java.io.FileNotFoundException;

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

public class Main {
    /**
     * For Fileoperations
     * Position in the file, which is read
     */
    private static long readStreamPosition;

    /**
     * This method handels the reading of data from a specific file.
     * 
     * @param file the file, to read from.
     * @param blockSize the length of the data-block, which should be read from the specified file.
     * @return the data read from the file.
     */
    public static byte[] readFile(File file, long blockSize) {
        FileInputStream fis;
        byte[] fileContent = null;

        try {
            fis = new FileInputStream(file);

            FileChannel fileChannel = fis.getChannel();

            int bytesToRead;
            fileChannel.position(readStreamPosition);

            int dataLen = fis.available();

            // if there is a zero block size specified, read the whole file
            if (blockSize == 0L) {
                bytesToRead = dataLen;
            } else {
                bytesToRead = (int) blockSize;
            }

            fileContent = new byte[bytesToRead];

            // reading the data
            for (int i = 0; i < bytesToRead; i++) {
                fileContent[i] = (byte) fis.read();
            }

            // storing read-position
            readStreamPosition = fileChannel.position();

            fis.close();
            fileChannel.close();

            // zero blockSize indicates, that reading of this file is completed,
            // stream position reset
            if (blockSize == 0L) {
                readStreamPosition = 0L;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileContent;
    }
}