简体   繁体   English

换行中的BufferedWriter数组元素

[英]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 例如:这是一个测试,这是2号测试线

The array here is btw already a string array. 这里的数组是btw已经是字符串数组。 String[] array = new String[5]; 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)
bw.write(array[i].toString());

Change that to 更改为

bw.write(array[i]);

and add 并添加

bw.newLine();

after that. 之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM