【问题标题】:Writing Multiple Lines To A File At Different Times在不同时间将多行写入文件
【发布时间】:2012-11-07 05:12:55
【问题描述】:

我已经完成了我的程序的基础知识。

这个想法是用户可以指定形状颜色宽度高度等。输入数据后,调用构造函数来创建输出,或者还有其他选项可以创建用户可以指定的输出。

我的目标是将所有这些输出放入一个文本文件中。

目前我创建了一个用于阅读的扫描仪:

static Scanner input = new Scanner(System.in);

然后在我的主要驱动方法中创建一个格式化程序:

public static void main(String[] args) {
        Formatter output = null;
        try{
            output = new Formatter("output.txt");
        }
        catch(SecurityException e1){
            System.err.println("You don't have" +
                    " write accress to this file");
            System.exit(1);
        }
        catch(FileNotFoundException e){
            System.err.println("Error opening or" +
                    " creating file.");
            System.exit(1);
        }

在每次我期望输出之后,我都放置了这段代码:

output.format("%s", input.nextLine());

最后我关闭文件

output.close()

文件已创建,但当前为空白。我知道我走在正确的轨道上,因为我尝试过这样做:

output.format("%d", i);

其中 i 是整数 0 并且文件写入正确。

但是,我似乎无法让它适用于整行,或者根本无法用于输出。

请帮忙!

【问题讨论】:

  • 您是否尝试过输出常量字符串而不是用户输入?或类似:output.format("Input: %s", input.nextLine());
  • 你打印了这个并看到有可用的值 System.out.println(input.nextLine())

标签: java file file-io


【解决方案1】:

我不是专家,但为什么你不能只使用“FileWriter”?
是因为您想捕获这些异常以向用户显示有用的信息吗?
还是我完全误解了这个问题? - 如果是这样,对不起,请忽略这个。

import java.io.FileWriter;
import java.io.IOException;

try
{
FileWriter fout = new FileWriter("output.txt"); // ("output.txt", true) for appending
fout.write(msg); // Assuming msg is already defined
fout.close();
}
catch (IOException e)
{
e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-22
    • 2011-11-30
    • 2018-03-12
    • 1970-01-01
    相关资源
    最近更新 更多