Write an array of strings into a file - Java java.io

Java examples for java.io:BufferedWriter

Description

Write an array of strings into a file

Demo Code

//package com.java2s;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] argv) {
        String filename = "Main.java";
        String[] output = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        writeTextFile(filename, output);
    }/*from  w w w  .j  a v a 2 s .c  om*/

    /**
     * Write an array of strings into a file
     * @param filename the file name
     * @param output the array of Strings
     */
    public static void writeTextFile(String filename, String[] output) {

        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(
                    new File(filename)));
            for (int i = 0; i < output.length; i++) {
                writer.write(output[i] + "\n");
            }
            writer.close();
        } catch (FileNotFoundException e) {
            System.err
                    .println("FileStringUtility.writeTextFile(String,String[]): Non posso creare o aprire il file: "
                            + filename);
        } catch (IOException e) {
            System.err
                    .println("FileStringUtility.writeTextFile(String,String[]): Non posso scrivere il file: "
                            + filename);
        }

    }

    /**
     * Write a string into a file
     *
     * @param filename the file name
     * @param output the output string
     */
    public static void writeTextFile(String filename, String output) {

        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(
                    new File(filename)));
            writer.write(output);
            writer.close();
        } catch (FileNotFoundException e) {
            System.err
                    .println("FileStringUtility.writeTextFile(String,String): Non posso creare o aprire il file: "
                            + filename);
        } catch (IOException e) {
            System.err
                    .println("FileStringUtility.writeTextFile(String,String): Non posso scrivere il file: "
                            + filename);
        }

    }
}

Related Tutorials