Java Program to write an array of strings to a file

Java 8Object Oriented ProgrammingProgramming

Here’s our file −

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

Now, consider a string array −

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

Write the above array to the file “demo.txt” −

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

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

Example

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();
   }
}

The output is as follows i.e. the text in the file is −

Output

ONE-TWO-THREE-FOUR-FIVE-SIX-SEVEN-EIGHT-NINE-
raja
Published on 25-Apr-2019 09:19:33
Advertisements