Java program to write an array of strings to a file


In this article, we will learn how to write an array of strings to a text file using Java. The program demonstrates how to use the FileWriter class to create and write a file. This method helps save data to a text file for future retrieval or processing.

FileWriter class: This class extends the OutputStreamWriter class and is used to write streams of characters to a file. It provides methods to write text data easily and efficiently, making it a key tool for handling file output operations in Java.

Problem Statement

Write a program in Java that writes an array of strings to a text file. The program should iterate through the array and write each element to the file −

Output

ONE-TWO-THREE-FOUR-FIVE-SIX-SEVEN-EIGHT-NINE

Steps to write an array of strings to a file

Below are the steps to write an array of strings to a file −

  • START
  • Instantiate a FileWriter object to create and write to the file E:/demo.txt.
  • Declare a string array with the values {"ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"}.
  • Iterate over the array using for loop and write each element to the file, appending a hyphen after each element.
  • Ensure that the FileWriter is properly closed to save the data.
  • STOP

Java program to write an array of strings to a file

The following is an example. Here, our file is “E:/demo.txt” −

import java.io.FileWriter;
public class Demo {
 public static void main(String[] argv) throws Exception {
FileWriter writer = new FileWriter("E:/demo.txt");
String arr[] = { "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" };
int len = arr.length;
for (int i = 0; i < len; i++) {
 writer.write(arr[i] + "-");
}
writer.close();
 }
}

Output

ONE-TWO-THREE-FOUR-FIVE-SIX-SEVEN-EIGHT-NINE-

Code Explanation

A FileWriter object is created to write to the specified file path "E:/demo.txt"

FileWriter writer = new FileWriter("E:/demo.txt");

A string array containing the values "ONE" to "NINE" is defined,

String arr[] = { "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" };

Writing to the file demo.txt a for loop is used to iterate over each element of the array. Each element is written to the file followed by a hyphen and FileWriter is closed to ensure that all data is properly written and saved to the file. Proper exception handling is included to handle any potential IOException.

int len = arr.length;
for (int i = 0; i < len; i++) {
 writer.write(arr[i] + "-");
}

Updated on: 24-Jul-2024

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements