FileWriter.write() 有没有办法在运行时继续在空格后写入字符串?

Is there a way for FileWriter.write() to continue writing strings after spaces in runtime?

当我尝试 运行 这篇文章时,

import java.io.*;
import java.util.Scanner;
import static java.lang.System.*;

class  CSWrite1
{
    public static void main(String[] args) throws IOException
    {
        Scanner input = new Scanner(in);
        out.print("Enter the filename\t>"); 
        String file = input.next();
        out.println("Enter the text");
        String text = input.next();  // IN:"Hello, How are you" --> "Hello,

        try(FileWriter fw = new FileWriter(file))
        { fw.write(text); }
    }
}

同时将文本输入为 "Hello, How are you" 文件仅写入“你好,。第一个 space 之后的剩余文本未写入文件。

Scanner使用分隔符,默认包含space。你可以做的(我不知道这有多优雅)是删除定界符。

Scanner input = new Scanner(System.in);
input.useDelimiter("");
String text=input.nextLine();
System.out.println(text);

这对我有用。这不是您的文件编写器,而是 Scanner 正在执行此操作。

以下对我有用:

import static java.lang.System.*;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class CSWrite1 {
    public static void main(String[] args) {
        try (Scanner input = new Scanner(in)) {
            out.print("Enter file name> ");
            String file = input.nextLine();
            try (FileWriter fw = new FileWriter(file)) {
                out.print("Enter text: ");
                String text = input.nextLine(); // IN:"Hello, How are you" --> "Hello,
                fw.write(text);
            }
            catch (IOException xIo) {
                xIo.printStackTrace();
            }
        }
    }
}