
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write an Array of Strings to a File in Java
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] + "-"); }