Write Int Array to a File in Java



To write an int array in a file in Java, we use write() method of the FileWriter class.

The FileWriter class in Java is part of the java.io package and is used to write character data to a file.

It provides constructors to create a file writer object and methods like write() to write data to the file. The close() method closes the file and releases resources. We will use the write() method to take an integer value, convert it to a string representation, and then write that string to the file. Thus, it writes the numeric values from the array to the file, one by one.

Steps to write int array to a file

Below are the steps to write an int array to a file ?

  • Begin by importing FileWriter class
  • Create the FileWriter object
  • Initialize the integer array and determine the array length
  • Iterate over the array using for loop and write each element to the file
  • Close the FileWriter object.

Java program to write int array to a file

In the below program, we are writing an integer array into a file -

import java.io.FileWriter;
import java.io.IOException;
public class Main {
    public static void main(String[] argv) {
        try {
            FileWriter writer = new FileWriter("input.txt"); // Changed file path
            Integer arr[] = {10, 20, 30, 40, 50};
            int len = arr.length;
            for (int i = 0; i < len; i++) {
                writer.write(arr[i] + "\t");
            }
            writer.close();
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output

1020304050

Code explanation

Here's our file ?

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

Now, consider an Integer array ?

Integer arr[] = { 10, 20, 30, 40, 50 };

Write the above array to the file "demo.txt" ?

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

This Java code writes an array of integers to a file named "input.txt". The program begins by importing the necessary classes, FileWriter and IOException. In the main method, a FileWriter object is created with the file name "input.txt". An integer array arr is declared and initialized with values. A for loop iterates over the array, writing each integer to the file followed by a tab character, using the write method. After writing all elements, the close method is called to release system resources. If any I/O error occurs, the code catches the IOException and prints an error message. 

Updated on: 2024-07-31T17:20:15+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements