0

テキスト ファイルの個々の行に大量のデータを書き込む必要がある Java アプリケーションがあります。これを行うために以下のコードを書きましたが、何らかの理由で、テキスト ファイルに何も書き込まれません。テキスト ファイルは作成されますが、プログラムの実行が終了してもテキスト ファイルは空のままです。以下のコードを修正して、実際に出力ファイルに必要な数の出力行が入力されるようにする方法を誰か教えてもらえますか?

public class MyMainClass{    
    PrintWriter output;

    MyMainClass(){    
        try {output = new PrintWriter("somefile.txt");}    
        catch (FileNotFoundException e1) {e1.printStackTrace();}    
        anotherMethod();
    }    

    void anotherMethod(){
        output.println("print some variables");
        MyOtherClass other = new MyOtherClass();
        other.someMethod(this);
    }
}

public class MyOtherClass(){
    void someMethod(MyMainClass mmc){
        mmc.output.println("print some other variables")
    }
}
4

3 に答える 3

1

他のコンストラクターを使用します。

output = new PrintWriter(new FileWriter("somefile.txt"), true);

JavaDocによると:

public PrintWriter(Writer out, boolean autoFlush)

新しい PrintWriter を作成します。

パラメーター:

out - 文字出力ストリーム
autoFlush - ブール値。true の場合、println、printf、または format メソッドは出力バッファをフラッシュします

于 2013-07-12T19:15:36.673 に答える
1

new PrintWriter(new PrintWriter("fileName"), true)データの自動フラッシュに他のコンストラクターを使用するか、書き込みが完了したら使用flush()close()ます

于 2013-07-12T19:19:15.830 に答える
1

どうやってこれをやろうとしているのか、私にはとても奇妙に思えます。文字列を受け取ってそれをファイルに書き込むメソッドを 1 つ作成してみませんか? このようなものはうまくいくはずです

public static void writeToLog(String inString)
{
    File f = new File("yourFile.txt");
    boolean existsFlag = f.exists();

    if(!existsFlag)
    {
        try {
            f.createNewFile();
        } catch (IOException e) {
            System.out.println("could not create new log file");
            e.printStackTrace();
        }

    }

    FileWriter fstream;
    try {
        fstream = new FileWriter(f, true);
         BufferedWriter out = new BufferedWriter(fstream);
         out.write(inString+"\n");
         out.newLine();
         out.close();
    } catch (IOException e) {
        System.out.println("could not write to the file");
        e.printStackTrace();
    } 


    return;
}
于 2013-07-12T19:21:31.093 に答える