Hi all,

I have taken some code to read a file into an Byte array, which is then returned to another part of my code, below is what i have.

public void jButton6_actionPerformed(ActionEvent e) {
    String Filelocation = "c:\\temp\\hello.txt";

    try{
      InputStream is = new FileInputStream(Filelocation);

      //get the size of the file
      long length = Filelocation.length();

      //range check to make sure length is not larger than int max val
      if(length > Integer.MAX_VALUE){
        XML(ErrorLog,"ERROR",2,0,"File trying to be sent is too large");
      }

      //create byte array
      byte[] DataStore = new byte[(int)length];

      //read
      int offset =0;
      int numread =0;
      while(offset < DataStore.length && (numread = is.read(DataStore,offset,DataStore.length-offset))>=0){
        offset += numread;
      }

      //close the input stream
      is.close();

      //call the set method of store the data
      try{
        ds.setdata(DataStore);
      }catch(Exception ex){
        XML(ErrorLog,"ERROR",2,0,"Error storing data : "+ex.toString());
        System.err.println("Error storing data");
      }
    }catch(Exception x){
      XML(ErrorLog,"ERROR",2,0,"Error serialising : "+x.toString());
      System.err.println("Error serialising");
    }
  }

I am also using the following to display the byte array.

public void jButton7_actionPerformed(ActionEvent e) {
    byte[] Data = ds.getdata();
    
    try{      
      FileOutputStream os = new FileOutputStream("c:\\temp\\HOE.txt");

      os.write(Data);
      os.close();
      
    }catch(Exception ex){
      XML(ErrorLog,"ERROR",2,0,"Error saving download file : "+ex.toString());
    }
     
  }

this is my problem, i think the read method is not reading all of the file, i say this as i put a test file in which had "this is a test file" written in. When it came to reading the byte array out it read "this is a test fi" and it seems odd that it is cutting of at 16 characters.

Is there something i am missing.

Any help would be greatly appreciated

Cheers.

String Filelocation = "c:\\temp\\hello.txt";
//get the size of the file
long length = Filelocation.length();

Get the size of what? File? Looks more like a String to me. A 16 character length string to be exact. Try this instead:

long length = is.available();

cheers,

I cant believe i did not see that :o .

Cheers again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.