Generate File with Random Content in Java


This tutorial will show you how to generate file with random content in Java. We 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.


Eclipse 2019-12, At least Java 1.8, wordnet-random-name 1.3

Creating Project

Create a gradle based project with name java-file-random-content in Eclipse.

Updating Build Script

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.


Generating Random Content

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

import java.nio.file.Files;
import java.nio.file.Path;
import org.kohsuke.randname.RandomNameGenerator;
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.

Creating File

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();


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

You can download source code.

Thanks for reading.

Leave a Comment