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

你怎么做这件事对我来说似乎很奇怪。你为什么不写一个方法来接受一个字符串然后把它写到你的文件中呢?像这样的东西应该可以正常工作

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 回答