Read file in byte array using FileInputStream

Want to learn quickly?
Try one of the many quizzes. More than Java 400 questions with detailed answers.


  • Hi,
    i am tryigb to figuer out the Math.random class, ti randomly creates numbers
    of type Double, right? so if i want to create numbers between 0-100, your second method should work, isn’t it?
    however, i copy paste your code the IDE, and it kept do give me the followign exceptions:

    at java.lang.ClassLoader.defineClass(Unknown Source)
    at Source)
    at Source)
    at$000(Unknown Source)
    at$ Source)
    at Method)
    at Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    Exception in thread “main”

    Thanks, Gil

  • [code]
    //As you might know, Math.random() generates a random double where X<0
    //To generate a random int using the same method (ie Math.random()) you do the //following:

    public class RandomInt{
    public static void main(String[] args){
    int random = (int)(Math.random()*10)+5; //*see bottom
    //the “(int)” parses the double to an int value
    //replace 10 with your range of numbers
    //(ie if you want a number between 5 and 15 the range is 10 [15-5]
    //replace the 5 with the staring number
    //(ie if you want the lowest number in the range to be 5 then add 5)
    //another eg.
    //int ran = (int)(Math.random()*100)-50;
    //will return a value in the range [-50;50]

    • It means generate a random number from the six consecutive numbers starting from 1. That means any number from 1,2,3,4,5,6. It does NOT mean any number from 1 to 6.

      How about this code?
      Will it give you random number from range 4-6? NO! It will give you random numbers from range 4-9! Reason: The six consecutive numbers starting from 4 are 4,5,6,7,8,9.

      If you want random numbers from 4-6, you must use this code:
      System.out.println((int)( (6-4+1) *Math.random())+4);

    • //I have make a simple program for Game by using your code
      import java.util.*;
      class RandomGame
      public static void main (String args[])
      Scanner scan=new Scanner(;
      int a=0;
      for(int j=0;j<5;j++)
      System.out.println(“Try Again”);
      System.out.println(“Game Over”);
      //Electrical Engineering Department

  • I was not initializing the byte array
    * byte fileContent[] = new byte[(int)file.length()]; *
    Now my prog is working.


Facebook Fans