IndexOutOfBoundsException  from FIS.read() method

I am trying to read 8 bytes from a FIS
According to the API for this method I should be able to read bytes 3 - 11 by using an offset of 3 and a length of 8 which is what
fin.read(l_data_array, i_offset, i_length); is supposed to do but if my offset is >0 then it fails.
Any ideas what is wrong?
( My file is approx 3KB so this is not the prob and the first method call does read 8 bytes )
    byte [] x = readBytesFromFile(0, 8); //ok
    byte [] x = readBytesFromFile(3, 8); //IndexOutOfBoundsException  thrown
   private byte [] readBytesFromFile( int i_offset, int i_length){
      byte[] l_data_array = new byte[i_length];
      try {
         File fd = new File(m_db);
         FileInputStream fin = new FileInputStream(fd);
         fin.read(l_data_array, i_offset, i_length);
         fin.close();
      catch (FileNotFoundException fnf) {
         System.out.println("File not found Exception");
      catch (IOException ioe) {
         System.out.println("IO Exception");
      return l_data_array;
   }error :
java.lang.IndexOutOfBoundsException
     at java.io.FileInputStream.readBytes(Native Method)
     at java.io.FileInputStream.read(FileInputStream.java:194)
     at Rule109_Automation_Package.Rule_109_Processor.readBytesFromFile(Rule_109_Processor.java:224)

Thanks for the replies folks.
The file I will be reading in will, for the first part of the development phase, serve as a a Database. So it is liable to become > 1MB.
Each record will be 1KB long, stored sequentially. So you are saying that if I want to read record No 999 I have to have a byte [] which can hold 999 * 1000 bytes. Seems a waste of resources ( Even though temporary ) that I can't move a pointer along the FIS and read say, bytes 9,000 to 10,000 into an array like ( byte[1000] ) instead of needing an array like ( byte [10,000] )
What kind of kinky reason do sun have for this?

Similar Messages

  • Buffered Reader read() method

    I'm trying to read a data file using the BufferedReader.read() method. Where the file is valid data I cast to a char and build up a string which then gets written to a flat file.
    Some of the bytes I need to read are pointers to a position in another file. These I want to read as integers, and I would expect to be able to use the value returned by the read() method directly.
    However I have a problem when the pointer byte has a value from hex 80 to 99 (I can see these using 'hex' on a LINUX system). The values returned are not what I would expect eg. where I would expect 128, I get 8364, expecting 130 I get 8218 and 131, I get 402.
    Above 159, things appear to be working as I would expect.
    Can anyone explain please
    Thanks,
    Martin

    BufferedReader should only be used to read character data. The value you get from the read method is not the value that was in the file. BufferedReader simply reads character data from an underlying Reader. Your underlying reader is probably an InputStreamReader or a FileReader. Both of those readers perform a transformation from the byte data to the characters using some character encoding. If you want the actual values, you must read them from the InputStream directly or use a DataInputStream

  • Problem with "System.in.read()" read() method!

    import java.io.*;
    import java.lang.*;
    class Count {
    public static void main(String args[]) throws IOException
    int count = 0;
    while (System.in.read()!=-1)
    count++;
    System.out.println("Input has " + count + " chars.");
    in this code the loop stucks and it increments the count variable infinitely of course as long as i hit enter. I am trying to understand the problem with read() method of system class's in object. in its definition it says; when the inputstream ends it returns -1, but in this code it does not return -1 ever. another question of mine is that what args[] array do? what does it store??

    Java doesn't bother much with the dos console and it a bit limited and limiting - no pretty colours /graphics options - just text - that's because java graduates to GUI's where there is laods of power and object /component support to do everything and everything you could imagine and more. System.in.read() ??? - thats a fine start!
    what args[] array do? what does it store??
    Good question !
    It provides a means of passing a parameter argument from the command line to the program - consider this;-public class HelloWithArgs {
       public static void main(String[] args) {
          System.out.println("Hello I am " + args[0]);
    }What does it do and how does it work? Or this;-public class HelloWithArgs2 {
       public static void main(String[] args) {
          try{
             String myName = args[0];
          catch(ArrayIndexOutOfBoundsException aob){
              System.out.print("No names: program will end");
              System.exit(0);
          System.out.println("Hello I am " + myName);
    }Study them and have fun. Though to answer the question -
    " public static void main(String[] args) {" // or
    " public static void main(String[] parameters) {"
    is the 'entry point' of all java programs, in order to do something it has to have a main() method and if youre going to pass on parameters, then why not a String array? If you think about it anything else would be fairly useless.

  • How can i take off my master card from my payment methods on my apple account

    my mastercard seems to be declined so i cant make any purchases but i also cant update any apps or download any free apps is there any way i can take off my mastervard from my payment methods?

    You can add an iTunes gift card, then remove the credit card. But, I'm afraid you're still gonna have to contact iTunes support to re-enable your account:
    http://www.apple.com/support/itunes/

  • How to retrieve data from a read-only Excel file

    Hi Developers,
    I'm trying to retrieve data from a read-only Excel file. I used the same code that I used to retrieve data from a normal Excel file, but it can't work.
    My code is as followed:
    try
    InputStream KpExcel = new FileInputStream("kp.xls");
    HSSFWorkbook Kpwb = new HSSFWorkbook(KpExcel);
    HSSFSheet Kpsheet = Kpwb.getSheetAt(0);
    catch(Exception e)
    e.printStackTrace();
    System.out.println("Exception: "+e.getMessage());
    The error I received is as followed:
    java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:494)
    at org.apache.poi.hssf.record.RecordFactory.createRecord(RecordFactory.java:224)
    at org.apache.poi.hssf.record.RecordFactory.createRecords(RecordFactory.java:160)
    at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:163)
    at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:210)
    at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:191)
    at photoproductionsystem.IncomingWIPPanel.getKp(IncomingWIPPanel.java:118)
    at photoproductionsystem.IncomingWIPPanel.<init>(IncomingWIPPanel.java:76)
    at photoproductionsystem.TabbedDisplay.<init>(TabbedDisplay.java:47)
    at photoproductionsystem.Display.create(Display.java:73)
    at photoproductionsystem.Display.init(Display.java:44)
    at photoproductionsystem.Display.main(Display.java:229)
    Caused by: java.lang.ArrayIndexOutOfBoundsException
    at java.lang.System.arraycopy(Native Method)
    at org.apache.poi.hssf.record.UnknownRecord.<init>(UnknownRecord.java:62)
    at org.apache.poi.hssf.record.SubRecord.createSubRecord(SubRecord.java:57)
    at org.apache.poi.hssf.record.ObjRecord.fillFields(ObjRecord.java:99)
    at org.apache.poi.hssf.record.Record.fillFields(Record.java:90)
    at org.apache.poi.hssf.record.Record.<init>(Record.java:55)
    at org.apache.poi.hssf.record.ObjRecord.<init>(ObjRecord.java:61)
    ... 15 more
    Can someone please help me with my problem? Thanks a lot in advance!

    Madeline wrote:
    how do I ask at Apache mailing list?I wonder why it seems to be a strange idea to some people to look at the software vendor's site for product support. :p
    http://poi.apache.org/mailinglists.html

  • Question about read method of InputStream

    Hello everyone,
    I am using read method of InputStream to read a stream from a remote machine. The network connection is not very stable (for example, a wireless network whose the signal strength is relatively low). I am wondering if read method returns -1 (which indicates the end of the stream has been reached), and if I invoke read method again on the same stream, is it possible to read any more data?
    I think maybe I can read some more data even if read returns -1 in one time because the connection is not very stable. I am looking for your comments to my problem in my specific situation.
    regards,
    George

    Thanks Adeodatus,
    Doc says This method blocks until input data is
    available, the end of the stream is detected, or
    an
    exception is thrown.
    http://java.sun.com/j2se/1.4.2/docs/api/java/io/InputS
    tream.html#read()
    I have not found any related parts in documents.
    http://java.sun.com/j2se/1.4.2/docs/api/
    Them's docs.
    if you're using a different version of java, replace
    the underlined portion with your version number.I am using JDK 1.3, and I have found related documents. But I can not find out where can I set timeout value of read operation. I am reading data from an HTTP InputStream. Can you help?
    regards,
    George

  • How to call a EJB method from Session bean method

    Hi all,
    I'm new to J2EE programming. I have a simple doubt .
    I have already created a lookup method for EJB bean in Session bean .
    My question is how to call a method of an ENTITY bean (say insertRow) from SESSION bean method(Say invoke_insertRow) .
    Please provide me an example code .
    Thanks in advance.

    InitialContext ctx = new InitialContext();
         GeneralEditor editor = (GeneralEditor) ctx
                        .lookup("GeneralEditorBean/remote");
              GeneralService service = (GeneralService) ctx
                        .lookup("GeneralServiceBean/remote");
              LanMu lm = new LanMu();
              lm.setName("shdfkhsad");
              editor.add(lm);

  • How to get value from Thread Run Method

    I want to access a variable from the run method of a Thread externally in a class or in a method. Even though I make the variable as public /public static, I could get the value till the end of the run method only. After that it seems that scope of the variable gets lost resulting to null value in the called method/class..
    How can I get the variable with the value?
    This is sample code:
    public class SampleSynchronisation
    public static void main(String df[])
    sampleThread sathr= new sampleThread();
    sathr.start();
    System.out.println("This is the value from the run method "+sathr.x);
    /* I should get Inside the run method::: But I get only Inside */
    class sampleThread extends Thread
         public String x="Inside";
         public void run()
              x+="the run method";

    I think this is what you're looking for. I hold up main(), waiting for the results to be concatenated to the String.
    public class sampsynch
        class SampleThread extends Thread
         String x = "Inside";
         public void run() {
             x+="the run method";
             synchronized(this) {
              notify();
        public static void main(String[] args) throws InterruptedException {
         SampleThread t = new sampsynch().new SampleThread();
         t.start();
         synchronized(t) {
             t.wait();
         System.out.println(t.x);
    }

  • Calling a method from a static method

    hello all,
    I'm calling a non-static method from a static method (from the main method). To overcome this i can make the method i am calling static but is there another way to get this to work without making the method that is being called static?
    all replies welcome, thanks

    When you call a non-static method, you are saying you are calling a method on an object. The object is an instance of the class in which the method is defined. It is a non-static method, because the instance holds data in it's instance variables that is needed to perform the method. Therefore to call this kind of method, you need to get (or create an instance of the class. Assuming the two methods are in the same class, you could do
    public class Foo
         public static void main(String[] args)
                Foo f = new Foo();
                f.callNonStaticMethod();
    }for instance.

  • How can I get the variable with the value from Thread Run method?

    We want to access a variable from the run method of a Thread externally in a class or in a method. Even though I make the variable as public /public static, I could get the value till the end of the run method only. After that scope of the variable gets lost resulting to null value in the called method/class..
    How can I get the variable with the value?
    This is sample code:
    public class SampleSynchronisation
         public static void main(String df[])
    sampleThread sathr= new sampleThread();
    sathr.start();
    System.out.println("This is the value from the run method "+sathr.x);
    // I should get Inside the run method::: But I get only Inside
    class sampleThread extends Thread
         public String x="Inside";
         public void run()
              x+="the run method";
    NB: if i write the variable in to a file I am able to read it from external method. This I dont want to do

    We want to access a variable from the run method of a
    Thread externally in a class or in a method. I presume you mean a member variable of the thread class and not a local variable inside the run() method.
    Even
    though I make the variable as public /public static, I
    could get the value till the end of the run method
    only. After that scope of the variable gets lost
    resulting to null value in the called method/class..
    I find it easier to implement the Runnable interface rather than extending a thread. This allows your class to extend another class (ie if you extend thread you can't extend something else, but if you implement Runnable you have the ability to inherit from something). Here's how I would write it:
    public class SampleSynchronisation
      public static void main(String[] args)
        SampleSynchronisation app = new SampleSynchronisation();
      public SampleSynchronisation()
        MyRunnable runner = new MyRunnable();
        new Thread(runner).start();
        // yield this thread so other thread gets a chance to start
        Thread.yield();
        System.out.println("runner's X = " + runner.getX());
      class MyRunnable implements Runnable
        String X = null;
        // this method called from the controlling thread
        public synchronized String getX()
          return X;
        public void run()
          System.out.println("Inside MyRunnable");
          X = "MyRunnable's data";
      } // end class MyRunnable
    } // end class SampleSynchronisation>
    public class SampleSynchronisation
    public static void main(String df[])
    sampleThread sathr= new sampleThread();
    sathr.start();
    System.out.println("This is the value from the run
    method "+sathr.x);
    // I should get Inside the run method::: But I get
    only Inside
    class sampleThread extends Thread
    public String x="Inside";
    public void run()
    x+="the run method";
    NB: if i write the variable in to a file I am able to
    read it from external method. This I dont want to do

  • Returning more than one value/object from an EJB method

    Hi,
    I have the follong method in the remote interface of my EJB:
    void createSomeObject( MyObject obj1, List returnList1, Map returnMap1);
    Since i want to return a List (returnList1) and a Map(returnMap1) from my EJB method "createSomeObjects", i am passing these as parameters thinking they will be passed by reference and the client(servlet) gets the changes the EJB made to these objects.
    But it doesn't seem to be working, the EJB is filling the List and Map objects and the servlet doesn't get it (pass by value problem).
    My understading is that, all parameters to an EJBs are passed by value(because they are remote calls, the RMI thing), let me know if this right.
    Is there any workaround apart from the following alternative?
    Alternatives:
    1. Wrap "List list1" and "Map map1" in another model and return this instead of passing them as parameters.
    Thanks
    Vasu

    My understading is that, all parameters to an EJBs
    are passed by value(because they are remote calls,
    the RMI thing), let me know if this right.Yes, that is correct - which you should know from your introduction to J2EE reading.
    Is there any workaround apart from the following
    alternative?
    Alternatives:
    1. Wrap "List list1" and "Map map1" in another model
    and return this instead of passing them as
    parameters.No.

  • How to remove the recursion from the following method

    Hi All,
    Can u plz help me to remove the recursion from the following method.
    The problem here is that recursion cann't be removed easily here as there is no any end condition.
    hopefully waiting for the help....
    Reema.
    private FilterStatement processCustomExpressions(FilterStatement statement,
              DistinguishedName tenant, LdapDao ldapDao)
              throws NameNotFoundException,
              LDAPServerException, NamingException {
         HashMap relMap = new HashMap();
         HashMap replaceMap = new HashMap();
         Vector relVec = null;
              FilterSubExpressions expressions = statement.getExpressions();
              FilterPartIterator it = (FilterPartIterator)expressions.iterator();
              while (it.hasNext()) {
                   FilterExpression e = (FilterExpression)it.next();
                   if (e instanceof CustomExpression) {
                        CustomExpression ce = (CustomExpression)e;
                        try {
                             FilterExpression fe = ce.createExpression();
                             if (fe instanceof RelationshipExpression) {
                                  RelationshipExpression re = (RelationshipExpression)fe;
                                  it.replace(re);
                                  relVec = (Vector) relMap.get(re.name);
                                  if(relVec == null) {
                                       relVec = new Vector();
                                       relVec.add(re);
                                  }else {
                                       relVec.add(re);
                                       it.remove();
                                  relMap.put(re.name, relVec);
                             } else if (fe instanceof SystemExpression) {
         SystemExpression se = (SystemExpression)fe;
         it.replace(se);
                        } catch (FilterEvaluationException fe) {
                             traceLogger.exception(Level.DEBUG_MIN, this,
                                  "processCustomExpressions(" + statement.toString() + ")", fe);
                             SystemLog.getInstance().logError(this,
                                  "processCustomExpressions(" + statement.toString() + ")", fe.getMessage());
              replaceRelationshipExpressions(statement, tenant, ldapDao, relMap);
              processContainerBasedExpressions(tenant, ldapDao, relMap, replaceMap);
              FilterSubStatements statements = statement.getStatements();
              FilterStatement temp = null;
              if (statements.size() != 0) {          
                   FilterPartIterator iter = (FilterPartIterator)statements.iterator();
                   while (iter.hasNext()) {
                        temp = (FilterStatement)iter.next();
                        temp = processCustomExpressions(temp, tenant, ldapDao);
                        iter.replace(temp);
              if(!replaceMap.isEmpty())
                   return replaceContainerBasedExpressions(statement, replaceMap);
              return statement;
         }

    I think one of the reasons that noone will reply to your posting is that you take it a bit too easy. First of all, please use the "code" button to format your code listings. Then it will look like this (see below) and everybody can at least read it!
    private FilterStatement processCustomExpressions(FilterStatement statement,
                                                    DistinguishedName tenant,
                                                    LdapDao ldapDao)
            throws NameNotFoundException, LDAPServerException, NamingException {
        HashMap relMap = new HashMap();
        HashMap replaceMap = new HashMap();
        Vector relVec = null;
        FilterSubExpressions expressions = statement.getExpressions();
        FilterPartIterator it = (FilterPartIterator) expressions.iterator();
        while (it.hasNext()) {
            FilterExpression e = (FilterExpression) it.next();
            if (e instanceof CustomExpression) {
                CustomExpression ce = (CustomExpression) e;
                try {
                    FilterExpression fe = ce.createExpression();
                    if (fe instanceof RelationshipExpression) {
                        RelationshipExpression re = (RelationshipExpression) fe;
                        it.replace(re);
                        relVec = (Vector) relMap.get(re.name);
                        if (relVec == null) {
                            relVec = new Vector();
                            relVec.add(re);
                        else {
                            relVec.add(re);
                            it.remove();
                        relMap.put(re.name, relVec);
                    else if (fe instanceof SystemExpression) {
                        SystemExpression se = (SystemExpression) fe;
                        it.replace(se);
                catch (FilterEvaluationException fe) {
                    traceLogger.exception(Level.DEBUG_MIN, this,
                                "processCustomExpressions("
                                + statement.toString()
                                + ")",
                            fe);
                    SystemLog.getInstance().logError(this,
                                "processCustomExpressions("
                                + statement.toString()
                                + ")",
                            fe.getMessage());
        replaceRelationshipExpressions(statement, tenant, ldapDao, relMap);
        processContainerBasedExpressions(tenant, ldapDao, relMap, replaceMap);
        FilterSubStatements statements = statement.getStatements();
        FilterStatement temp = null;
        if (statements.size() != 0) {
            FilterPartIterator iter = (FilterPartIterator) statements.iterator();
            while (iter.hasNext()) {
                temp = (FilterStatement) iter.next();
                temp = processCustomExpressions(temp, tenant, ldapDao);
                iter.replace(temp);
        if (!replaceMap.isEmpty())
            return replaceContainerBasedExpressions(statement, replaceMap);
        return statement;
    }Second, when you cannot understand your own code anymore, simplify it! As far as I can see, there are two "main" processes (i.e. loops) in your method, where the second one calls the method recursively. Split the method into two. Furthermore, write a third method that processes the iterated elements and call that method from out of the loops.
    I did'nt analyse your method and have no idea what it does at all. I'm merely telling my first impression.
    Good luck.

  • How do you call a java class from the main method in another class?

    Hi all,
    How do you call a java class from the main() method in another class? Assuming the two class are in the same package.
    Thanks
    SI
    Edited by: okun on May 16, 2010 8:40 PM
    Edited by: okun on May 16, 2010 8:41 PM
    Edited by: okun on May 16, 2010 8:47 PM

    georgemc wrote:
    To answer your impending question, either the method you're calling has to be static, or you need an instance of that other class to invoke it against. Prefer the latterAnd to your impending question after that: no, don't use the Singleton pattern.

  • Passing array from JS to method of applet

    There is unable in IE pass array of values from javascript to method of applet, but in Mozilla it's working fine. In IE i have got exception:
    Exception:
    java.lang.Exception: setTest{0} :no such method exists
         at sun.plugin.com.JavaClass.getMethod1(Unknown Source)
         at sun.plugin.com.JavaClass.getDispatcher(Unknown Source)
         at sun.plugin.com.DispatchImpl.invokeImpl(Unknown Source)
         at sun.plugin.com.DispatchImpl$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.plugin.com.DispatchImpl.invoke(Unknown Source)
    java.lang.Exception: java.lang.Exception: setTest{0} :no such method exists
         at sun.plugin.com.DispatchImpl.invokeImpl(Unknown Source)
         at sun.plugin.com.DispatchImpl$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at sun.plugin.com.DispatchImpl.invoke(Unknown Source)
    JavaScript code:
    var testArr=[];
        testArr[0]=1;
        testArr[1]=2;
        testArr[2]=3;
        document.sync.setTest(testArr);
    Applet method:
    public void setTest(Object[] test){
            System.out.println("Test "+test.length);
            for (Object o: test){
                System.out.println(o.toString());
        }How do passing in IE?

    yes, MAYSCRIPT just allow to call methods. but as i know it's unable to pass simply array from js to applet and from applet to js. so i convert array of values to String and in applet i use StringTokenizer to parsing. Thanks. ;)

  • How to measure time spent on socket read() method ?

    Hi,
    I have a socket waiting for input stream from a remote host :
    // method blocks until some input is available
    int count = socket_host.getInputStream().read(bytes);
    I want to know how much time it took to receive "count" bytes from remote host.
              t1 = System.nanoTime();
              int count = socket_host.getInputStream().read(bytes);
              t2 = System.nanoTime();
    (t2-t1) of course is not the answer, because t1 needs to start when read method actually stop waiting..
    I need some kind of call back, in order to know when input starts coming..
    how would you do that accuratly ?
    thanks for help !!

    thanks ejp , I followed your idea :
         count1=socket_host.getInputStream().read(bytes,0,1);
         t1 = System.nanoTime();
         count2=socket_host.getInputStream().read(bytes,1,bytes.length-1);
         t2 = System.nanoTime();
         if (count1==1 && count2>0)
              count=count2+1;
         else if (count1==-1 || count2==-1)
              count=-1;After I compute speed (with t2-t1 and count given to that method)
         public static double computeSpeed(double nanosec,double nbbytes){
              if (nanosec==0)
                   return 0;
              double speedkilobytespersec=nbbytes/nanosec*1000000;
              return speedkilobytespersec;
         }But speed results are very erratic and sometimes superior to 100 MBytes /sec , which is not possible with my connection.
    Somehow, I have the feeling that when t1 is triggered, it is already too late, many bytes are already arrived, and results is not accurate.
    It would need a lower level trigger, wouldn't it ?
    thanks

Maybe you are looking for

  • IPhone not being recognized by iTunes, after 10.5 upgrade

    I finally (!!) upgraded to Leopard and am now at 10.5.5. All has gone smoothly, with one exception. When I connect my iPhone via the provided USB cable, iTunes doesn't recognize it. iPhoto does, and the iPhone does charge while connected to the USB c

  • Nokia 7370 Urgent help needed

    Hi, My nokia is having some serious issues and i dont know how to fix it. it freezes to a white screen with just the battery sign on top i have to turn it off then on to unfreeze it, when it does unfreeze on its own it comes up with a message saying

  • Drag and Drop Cursor changes - not working

    I have fully implemented a working drag and drop Swing application, but I am running into problems with the cursor. My application has some drop targets that set the cursor to DragSource.DefaultCopyNoDrop, and some that set it to DragSource.DefaultCo

  • WFP Dimension loads in planning

    should the employee and entity dimension loaded every month as part of actual data loads or should they be loaded only at the begining of the planning cycle ?  What happens if the 2 cycles overlap  if planning cycle is jun - jul (12 mths) will the  d

  • Shared Photo Stream as default stream?

    We have 4 iPhones and was hoping to set up Photo Stream so each phone could see every other phones photos.  Do photos have to be shared manually or is there a setting (I am missing) that will simply push ALL photos taken to the shared photo stream?