In this post under Java, I will show with example how to create a text file of user specified size with random data.
Below is the complete code for you example
Main class
1 package io;
2
3 import java.io.BufferedWriter;
4 import java.io.File;
5 import java.io.FileWriter;
6 import java.io.IOException;
7 import java.util.Random;
8
9 public class IOExample1 {
10 private Random random;
11
12 public IOExample1() {
13 random = new Random();
14 }
15
16 public static void main(String[] args) throws IOException {
17 if((args.length == 0) || (args.length == 1)) {
18 throw new IllegalArgumentException("file Size (in MB) and file name must be mentioned");
19 }
20 IOExample1 ioExample1 = new IOExample1();
21 int fileSize = Integer.parseInt(args[0]);
22 ioExample1.createFile(fileSize, args[1]);
23 }
24
25 public void createFile(int fileSize, String fileName) throws IOException {
26 File file = new File(fileName);
27 int fileSizeInMB = fileSize * 1000 * 1000;
28 try(FileWriter fileWriter = new FileWriter(file);
29 BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
30 char ch = (char) getRandomNumber();
31 for(int i = 0; i < fileSizeInMB; i++) {
32 bufferedWriter.write(ch);
33 ch = (char) getRandomNumber();
34 }
35 bufferedWriter.flush();
36 }
37 }
38
39 public int getRandomNumber() {
40 return random.nextInt(127 - 33) + 33;
41 }
42 }
In the above code, main method, line 17, I am asking for file size (in MB) and name of the file to be created as program arguments.
If both are not present I am throwing an “IllegalArgumentException” exception.
At line 20, I am creating an instance of “IOExample1” class.
At line 21, getting the file size from the command line arguments.
At line 22, calling “createFile” method on “IOExample1” class and passing “fileSize” and “fileName” as a paramter.
In the “createFile” method, I create a text file with random character from ASCII table within the range from 33 to 126 number.
The random character is returned by the “getRandomNumber” method. This method will return int values between 33 to 126 which is casted to character at line 33 before writing to the text file.
The reason behind choosing the ASCII table range from 33 to 126 is that all the letters within this range have single character. Single character is stored as a single byte in the text file.
In this way we can create a text file of user specified size with random data.