Creating a text file filled with random integers in Java

Stupid question, maybe. But I try to fill an empty text file with 512 integers, each on every new line. I was able to randomize and write them into the file, but they create a huge pile of numbers of what I have wished. Can anyone help me correct my code?

import java.util.*;

public class Randomizer {

      public static void main() {
        // The target file
        File out = new File("random.txt");
        FileWriter fw = null;
        int n = 512;
        // Try block: Most stream operations may throw IO exception
        try {
            // Create file writer object
            fw = new FileWriter(out);
            // Wrap the writer with buffered streams
            BufferedWriter writer = new BufferedWriter(fw);
            int line;
            Random random = new Random();
            while (n > 0) {
                // Randomize an integer and write it to the output file
                line = random.nextInt(1000);
                writer.write(line + "n");
            // Close the stream
        } catch (IOException e) {

Content of random.txt at the end of the run:
9463765593113665333437829621346187993554694651813319223268147794541131427390 etc.

Source: java

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.