This forum is in archive mode. You will not be able to post new content.

Author Topic: [java]trying to compile this source code  (Read 1921 times)

0 Members and 2 Guests are viewing this topic.

Offline gh0st

  • Sir
  • ***
  • Posts: 575
  • Cookies: 8
  • #DEDSec
    • View Profile
[java]trying to compile this source code
« on: July 21, 2011, 05:41:01 AM »
Code: [Select]
// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

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

    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
        // File is too large
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file "+file.getName());
    }

    // Close the input stream and return bytes
    is.close();
    return bytes;
}
thanks to http://www.exampledepot.com/egs/java.io/File2ByteArray.html
 
well first I replace "getBytesFromFile(File file)" how is the correct way to replace that "file file"? example.txt? bin/example.txt?
 
and here? "FileInputStream(file);"

what about here? long length = file.length();"
 
and the header would be java.i/o? any suggestions will be appreciated

iMorg

  • Guest
Re: [java]trying to compile this source code
« Reply #1 on: July 21, 2011, 05:57:04 AM »
What are you replacing it all with. That looks like a finished example.

The function must be called with a File object. since
Code: [Select]
getBytesFromFile(File file)declares the argument as a File object named "file". I think when you create a new file object you just call the File constructor with a string containing the path to the file.

I would use the header java.io.*, unless you are wanting to go for efficiency than only use what you need and call java.io.File.

Offline gh0st

  • Sir
  • ***
  • Posts: 575
  • Cookies: 8
  • #DEDSec
    • View Profile
Re: [java]trying to compile this source code
« Reply #2 on: July 21, 2011, 07:59:11 AM »
solved http://www.thenewboston.com/?p=1207&pOpen=tutorial Im moving on now to byte stream reading

xor

  • Guest
Re: [java]trying to compile this source code
« Reply #3 on: July 21, 2011, 02:19:14 PM »
Ghost if you have any Java related questions, try and hit me up on the IRC.

 



Want to be here? Contact Ande, Factionwars or Kulverstukas on the forum or at IRC.