Creating a text file filled with random integers in Java
Silly question, maybe. But I'm trying to fill a blank text file with 512 integers, each on every new line. I was able to randomize and write them to a file, but they create a huge bunch of numbers, which is what I wanted. Can anyone help me fix my code?
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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");
n--;
}
// Close the stream
writer.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
}
}
The content of random.txt at the end of the run: 9463765593113665333437829621346187993554694651813319223268147794541131427390, etc.
source to share
You seem to be using line endings on Windows, different on Unix / Windows / Classic Mac.
Try \ r \ n for Windows based systems, or try opening a .txt file in Wordpad instead of Notepad. \ N is commonly used on Unix systems, and the Notepad app included with Windows has been known to not handle them well.
source to share
Check this line from the javadoc for BufferedWriter
:
Method A is provided
newLine()
, which uses the platform's own line separator concept as defined by the line.separator system property. Not all platforms use the newline character ('\n'
) for line termination. Therefore, calling this method to terminate each output line is preferable to write the newline character directly.
source to share