Quatsch
Quatsch

Reputation: 392

BufferedWriter array elements in new line

looked through a lot of similar subjects, couldn't find something that works for me :/

All I want to do is to write every element of an array to a text file.

    Arrays.toString(array);

That code gives me every element in one line and also brackets around the whole list of elements. Thats not what I want.

The elements of the array are only text. For example: this is a test this is testline number 2

The array here is btw already a string array. String[] array = new String[5];

My code so far is following:

    public void dateiausgeben() throws NullPointerException {
    try {

        FileWriter fw = new FileWriter("neueDatei.txt");
        BufferedWriter bw =  new BufferedWriter(fw);

        for (int i = 0; i < array.length;i++) {
            //String str = array[i].toString();
            //System.out.println("array 0 ="+array[0]+"\n array 1 ="+array[1]+"\n array 2= "+array[2]+"\n array 3="+array[3]);

            bw.write(array[i].toString());

        }
        bw.close();
    }
    catch (IOException e){
        e.printStackTrace();
    }

}

I tried also other stuff out. I also want to keep it as simple as possible.

Stack Trace

    Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Unknown Source)
at Kapitel3_3.readfile.dateiausgeben(readfile.java:61)
at Kapitel3_3.DateiKopierer.main(DateiKopierer.java:15)

Upvotes: 1

Views: 3020

Answers (1)

user207421
user207421

Reputation: 310936

bw.write(array[i].toString());

Change that to

bw.write(array[i]);

and add

bw.newLine();

after that.

Upvotes: 2

Related Questions