首页 > 解决方案 > FileWriter.write() 有没有办法在运行时继续在空格后写入字符串?

问题描述

当我试图运行这件作品时,

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

在将文本输入为“你好,你好吗”时,文件只写有“你好,”。第一个空格之后的剩余文本不会被写入文件中。

标签: javafilewriter

解决方案


以下对我有用:

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

推荐阅读