How do I create and write data into text file?

Here is a code example for creating text file and put some texts in it. This program will create a file called write.txt. To create and write a text file we do the following steps:

File file = new File("write.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

Below is the complete code snippet:

package org.kodejava.io;

import java.io.*;

public class WriteTextFileExample {
    public static void main(String[] args) {
        File file = new File("write.txt");

        try (Writer writer = new BufferedWriter(new FileWriter(file))) {
            String contents = "The quick brown fox" + 
                System.getProperty("line.separator") + "jumps over the lazy dog.";

            writer.write(contents);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

To read a text file see the following example: How do I read a text file using BufferedReader?.

How do I read a text file using BufferedReader?

The code snippet below is an example of how to read a text file using BufferedReader class from the java.io package. This snippet read a text file called README.md and print out its content.

To create an instance of java.io.BufferedReader we do the following steps:

File file = new File("README.md");
FileReader fileReader = new FileReader(file));
BufferedReader bufferedReader = new BufferedReader(fileReader);

Let’s see the complete code snippet.

package org.kodejava.io;

import java.io.*;

public class ReadTextFileExample {
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    public static void main(String[] args) {
        File file = new File("README.md");
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            StringBuilder contents = new StringBuilder();
            String text;
            while ((text = reader.readLine()) != null) {
                contents.append(text).append(LINE_SEPARATOR);
            }

            System.out.println(contents.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

You can also try to use the following example to read a file, How do I read text file content line by line using commons-io?. To create and write a text file see the following example: How do I create and write data into text file?.

How do I read a configuration file using java.util.Properties?

When we have an application that used a text file to store a configuration, and the configuration is typically in a key=value format then we can use java.util.Properties to read that configuration file.

Here is an example of a configuration file called app.config:

app.name=Properties Sample Code
app.version=1.0

The code below show you how to read the configuration.

package org.kodejava.util;

import java.io.*;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;

public class PropertiesExample {
    public static void main(String[] args) {
        Properties prop = new Properties();
        try {
            // the configuration file name
            String fileName = "app.config";
            ClassLoader classLoader = PropertiesExample.class.getClassLoader();

            // Make sure that the configuration file exists
            URL res = Objects.requireNonNull(classLoader.getResource(fileName),
                "Can't find configuration file app.config");

            InputStream is = new FileInputStream(res.getFile());

            // load the properties file
            prop.load(is);

            // get the value for app.name key
            System.out.println(prop.getProperty("app.name"));
            // get the value for app.version key
            System.out.println(prop.getProperty("app.version"));

            // get the value for app.vendor key and if the
            // key is not available return Kode Java as
            // the default value
            System.out.println(prop.getProperty("app.vendor","Kode Java"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The code snippet will print these results:

Properties Sample Code
1.0
Kode Java

How do I convert a collection object into an array?

To convert collection-based object into an array we can use toArray() or toArray(T[] a) method provided by the implementation of Collection interface such as java.util.ArrayList.

package org.kodejava.util;

import java.util.List;
import java.util.ArrayList;

public class CollectionToArrayExample {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        words.add("Kode");
        words.add("Java");
        words.add("-");
        words.add("Learn");
        words.add("Java");
        words.add("by");
        words.add("Examples");

        String[] array = words.toArray(new String[0]);
        for (String word : array) {
            System.out.println(word);
        }
    }
}

Our code snippet result is shown below:

Kode
Java
-
Learn
Java
by
Examples

How do I convert an array into a collection object?

To convert array based data into List / Collection based we can use java.util.Arrays class. This class provides a static method asList(T... a) that converts array into List / Collection.

package org.kodejava.util;

import java.util.Arrays;
import java.util.List;

public class ArrayAsListExample {
    public static void main(String[] args) {
        String[] words = {"Happy", "New", "Year", "2021"};
        List<String> list = Arrays.asList(words);

        for (String word : list) {
            System.out.println(word);
        }
    }
}

The results of our code are:

Happy
New
Year
2021