FileWriter始终在新行中写入

时间:2015-05-21 02:37:44

标签: java string filewriter bufferedwriter

我有一个大问题:我正在尝试写一个单词或短语但是当我的程序收到短语时,它会在文件中每行写一个单词......

import java.io.*;
import java.util.Scanner;
public class Hola{
    public static void main(String[] args) throws IOException{
        FileWriter fw = new FileWriter("Pru2.java");
        BufferedWriter bw = new BufferedWriter(fw);

        Scanner sc = new Scanner(System.in);
        String palabra = sc.next();

        while(palabra.compareTo("z")!=0){
            bw.write(palabra);
            bw.newLine();
            bw.flush();
            palabra = sc.next();
        }

        bw.close();
    }
}

当我在cmd中写这个短语(“这是一个例子”)然后我打开文件时,这就是我读到的:

This
is
an
example

我真的很感激任何帮助! 非常感谢你。

1 个答案:

答案 0 :(得分:0)

希望以下代码有帮助

public static void main(String[] args) throws IOException {
    FileWriter fw = new FileWriter("Pru2.txt");
    BufferedWriter bw = new BufferedWriter(fw);

    Scanner sc = new Scanner(System.in);
    String palabra = sc.next();

    while (palabra.compareTo("z") != 0) {
        bw.write(palabra);
        bw.write(" "); //add this line to have space
        //bw.newLine();//comment this line
        palabra = sc.next();
    }
    bw.flush();
    bw.close();
}