簡體   English   中英

在不同時間將多行寫入文件

[英]Writing Multiple Lines To A File At Different Times

我已經完成了程序的基礎知識。

這個想法是用戶可以指定形狀,顏色,寬度,高度等。輸入數據后,將調用構造函數來創建輸出,或者還有其他選項可以創建用戶指定的輸出。

我的目標是將所有這些輸出都輸出到文本文件中。

目前,我創建了一個掃描儀來讀取:

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

然后在主驅動程序方法中,創建一個Formatter:

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的整數,文件可以正確寫入。

但是,我似乎無法使它適用於整條線,也不能完全適用於輸出。

請幫忙!

我不是專家,但是為什么不能僅使用“ 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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM