Generate File With Random Content In Java

File with Random Content

This tutorial will show you how to generate file with random content in Java. I will generate random content in a text file using wordnet-random-name API in Java. You can set limit to any number of lines for the text file to hold generated random content in it.

This kind of random content is a quick and an easy to use for your application purpose where you need lots of content for performing testing. So this ready-made API generates large content to solve your purpose.


At least Java 1.8/19, wordnet-random-name 1.3/1.5, Maven 3.6.3/3.8.5, Gradle 6.5.1 – 6.7.1

Project Setup

Create a gradle or maven based project with name java-file-random-content in your favorite tool or IDE.

Update the generated build.gradle script to include the required dependency.

plugins {
    id 'java-library'

sourceCompatibility = 12
targetCompatibility = 12

repositories {

dependencies {
    implementation 'org.kohsuke:wordnet-random-name:1.3'

If you create maven based project then use below maven dependency in your pom.xml file.

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns=""





Random Content

Create below Java class to generate a text file with random content. The size of the file you can control using the number of line you want to put into the file using random content.


public class RandomFileContentGenerator {
	private static File root = new File("./data");
	private final String fileName;
	private final int lines;
	RandomFileContentGenerator(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
		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",,;

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.

File Generation

Now create the below main class to create file with random content in it.


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

Testing the Program

Run the above main class and once the main class stops then verify the generated file under java-file-random-content/data/large.txt.

The size of the generated file with random content is almost 313 MB.

Source Code


Leave a Reply

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