Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.io.File;

import java.io.RandomAccessFile;

public class Main {
    public static byte[] readFromFile(String fileName, int offset, int len) {
        if (fileName == null) {
            return null;
        }

        File file = new File(fileName);
        if (!file.exists()) {
            //WLog.i(FileUtils.class, "readFromFile: file not found");
            return null;
        }

        if (len == -1) {
            len = (int) file.length();
        }

        if (offset < 0) {
            //WLog.e(FileUtils.class, "readFromFile invalid offset:" + offset);
            return null;
        }
        if (len <= 0) {
            //WLog.e(FileUtils.class, "readFromFile invalid len:" + len);
            return null;
        }
        if (offset + len > (int) file.length()) {
            //WLog.e(FileUtils.class, "readFromFile invalid file len:" + file.length());
            return null;
        }

        byte[] b = null;
        try {
            RandomAccessFile in = new RandomAccessFile(fileName, "r");
            b = new byte[len];
            in.seek(offset);
            in.readFully(b);
            in.close();

        } catch (Exception e) {
            // WLog.e(FileUtils.class, "readFromFile : errMsg = " + e.getMessage());
            e.printStackTrace();
        }
        return b;
    }
}