Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java write text file

farenda 2016-02-12 0

Problem:

How to write text file in Java? java.io have a number of useful classes for working with files, one of them is FileWriter that we’re going to show in this post. Read on!

Solution:

In the following program we’re going to generate some data and write them into a CSV file. To write text file in Java use FileWriter. For better performance always wrap it in BufferedWriter like in the example.

The program is using FileWriter in two ways:

  1. To create a “highscores.csv” file with generated data
  2. To reopen the file for appending to add some more data.
package com.farenda.java.io;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;

public class WriteTextFileExample {

    private static final Random rand = new Random();

    public static void main(String[] args) throws IOException {
        Map<String,Integer> playersPoints = generateSampleData();

        String scoreFile = "highscores.csv";

        // Create a new file and override when already exists:
        try (Writer output = openWriter(scoreFile)) {
            writeHeader(output);
            for (Entry<String, Integer> player : playersPoints.entrySet()) {
                output.write(formatRow(player));
            }
        }

        Entry<String, Integer> newUser =
                new SimpleImmutableEntry<>("newUser", generatePoints());
        // Reopen the file but for appending:
        try (Writer output = openWriter(scoreFile, true)) {
            output.write(formatRow(newUser));
        }
    }

    private static Map<String,Integer> generateSampleData() {
        Map<String,Integer> playersPoints = new LinkedHashMap<>();
        for (int i = 1; i <= 5; ++i) {
            playersPoints.put("user" + i, generatePoints());
        }
        return playersPoints;
    }

    private static int generatePoints() {
        return rand.nextInt(1000) + 1;
    }

    private static void writeHeader(Writer output) throws IOException {
        output.append("#name,points").append(System.lineSeparator());
    }

    private static BufferedWriter openWriter(String fileName)
            throws IOException {
        return openWriter(fileName, false);
    }

    private static BufferedWriter openWriter(String fileName, boolean append)
            throws IOException {
        // Don't forget to add buffering to have better performance!
        return new BufferedWriter(new FileWriter(fileName, append));
    }

    private static String formatRow(Entry<String, Integer> player) {
        String row = String.format("%s,%s%n",
                player.getKey(), player.getValue());
        System.out.print("Adding row: " + row);
        return row;
    }
}

The result of running the above program:

Adding row: user1,757
Adding row: user2,482
Adding row: user3,155
Adding row: user4,269
Adding row: user5,31
Adding row: newUser,680

And the contents of the created file:

$> cat highscores.csv
#name,points
user1,757
user2,482
user3,155
user4,269
user5,31
newUser,680
Share with the World!
Categories Java Tags java, java-io
Previous: Java File list files
Next: Java read text file

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored