This tutorial will show you how to generate random content for creating a text file using Java technology. We will also use library wordnet-random-name to generate human friendly random identifiers.

For more information on wordnet-random-name please read https://github.com/kohsuke/wordnet-random-name

Prerequisites

Java 8
wordnet-random-name library

Maven dependency

<dependency>
 <groupId>org.kohsuke</groupId>
 <artifactId>wordnet-random-name</artifactId>
 <version>1.3</version>
</dependency>

Create below Java class to generate a text file with random content.

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.kohsuke.randname.RandomNameGenerator;

public class RandomFileGenerator {

	private static File root = new File("./data");
	private final String fileName;
	private final int lines;

	RandomFileGenerator(String fileName, int lineCount) {
		this.fileName = fileName;
		this.lines = lineCount;
	}

	void generate() throws IOException {
		Path fullPath = new File(root, fileName).toPath();
		// make sure file exists
		Files.createDirectories(fullPath.getParent());

		RandomNameGenerator rng = new RandomNameGenerator(0);

		try (BufferedWriter bw = Files.newBufferedWriter(fullPath)) {
			for (int i = 0; i < lines; ++i) {
				String line = String.format("%s %s%n", rng.next(), rng.next());
				bw.write(line);
			}
		}
	}

}

The file root directory is data, where the file will be created, under the project root directory. The constructor requires file name and number of lines to be generated randomly in the given file name.

Now create the below main class to test the file generation.

import java.io.IOException;

public class GenerateLargeFile {

	public static void main(String[] args) throws IOException {
		new RandomFileGenerator("large.txt", 10000000).generate();
	}

}

Run the above main class and once the main class stops then verify the generated file <project root directory>/data/large.txt.

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *