Home > other >  Generating n random integers and putting them in a byte array, printing to file
Generating n random integers and putting them in a byte array, printing to file

Time:03-11

Currently working on a little project; as part of it I am creating a function called randomNumberGenerator which takes one parameter; string fileName which the name of the file/path that the user wants the integers to be written to. 10,000 random integers with a value between 0 and 100,000. From here, I want to convert the integers into an array of 4 bytes; and print the result in the filename which the user has passed into the function.

I've worked out how to generate the random numbers successfully, however I'm not able to convert it to a byte array successfully. Below is the function so far:

public void randomNumberGenerator(String fileName) throws FileNotFoundException {


    try {
      PrintWriter printWriter = new PrintWriter(fileName, StandardCharsets.UTF_8);
      Random random = new Random();
      for(int i=0; i<10000; i  ) {
        byte [] bytes = ByteBuffer.allocate(4).putInt(random.nextInt(100000)).array();
        printWriter.println(Arrays.toString(bytes));

      }
      printWriter.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

When I try running my code thus far, I'm getting the error java.lang.NumberFormatException: For input string: "[0, 0, -115, -120]" - I've tried to fix this by doing printWriter.println(Arrays.toString(bytes)); instead, as I thought Arrays.toString was causing the error but I still can't get the function to turn the integers to a byte array succesffuly from there.

If anybody could advise me on what to do or where I'm going wrong, I'd appreciate it.

CodePudding user response:

I believe this is what you were looking for, I'd just like to point out that the byte data type can hold values from -128 to 127 so for this program, you'd likely want to use a short as they can hold up to 32k.

I'll also point out that in most cases you don't need to mark the method as throwing the FNTE as you're already handling the exception within (although you could still mark it as throwing FNTE if you want to further handle it from wherever you're calling it from)

    public static void main(String args[]) {
        //Call the method, pass in the required args
        genRandomNums(5, 4, 10000, "nums.txt");
    }

    public static void genRandomNums(int amount, int size, int maxVal, String fileName){
        try {
            //Create a file object and set the path to the passed file name
            File file = new File(fileName);
            //Create object of filewriter which will be used to write to the file
            FileWriter fw = new FileWriter(file);

            //Create an object of random, used to generate the random numbers
            Random random = new Random();
            
            //This loop controls how many arrays are created
            for(int i = 0; i < amount; i  ){

                //Array to store the temp numbers, change this to int/long if you want to store above 32k value mark
                short tempArr[] = new short[size];
                
                //This loop controls setting the actual elements of the array
                for (int j = 0; j < size; j  ){
                    tempArr[j] = (short) random.nextInt(maxVal);
                }

                //Write the array to the file, add a new line so each array is separated
                fw.write(Arrays.toString(tempArr)   "\n");
            }

            //Close and save the file
            fw.close();

        }catch (IOException ex){
            ex.printStackTrace();
        }
    }

CodePudding user response:

Try it like this. The values will be between -128 and 127 inclusive. Separated by a comma and a space.

public static void randomNumberGenerator(String fileName) throws FileNotFoundException {
    
    Random random = new Random();
    try (PrintWriter printWriter = new PrintWriter(fileName, StandardCharsets.UTF_8)) {
        printWriter.print(random.nextInt(255)-128); 
        for(int i=0; i<39_999; i  ) {
                    printWriter.printf(", %d", random.nextInt(255)-128);        
        }
    
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

}
  • Related