【问题标题】:FileWriter writes always in a new lineFileWriter 总是在新行中写入
【发布时间】:2023-03-17 19:25:01
【问题描述】:

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

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”)然后我打开文件时,我看到的就是这个:

This
is
an
example

我将非常感谢任何帮助! 非常感谢。

【问题讨论】:

  • 呃,不要这么频繁地给newLine()打电话?您也不应该在循环内冲洗。并且不要调用文件.java,而不是。

标签: java string filewriter bufferedwriter


【解决方案1】:

希望下面的代码有所帮助

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

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 2014-03-13
    • 2011-12-21
    • 2020-09-29
    • 2013-09-04
    • 2016-01-30
    • 1970-01-01
    • 2015-11-24
    • 2011-06-25
    相关资源
    最近更新 更多