繁体   English   中英

使用PrintWriter将字符串写入日志文件

[英]using PrintWriter to write strings to log file

我有一个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")
    }
}

使用其他构造函数:

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

根据JavaDoc

public PrintWriter(Writer out, boolean autoFlush)

创建一个新的PrintWriter。

参数:

out-字符输出流
autoFlush-一个布尔值; 如果为true,则println,printf或format方法将刷新输出缓冲区

使用其他构造函数new PrintWriter(new PrintWriter("fileName"), true)进行自动刷新数据,或在完成编写后使用flush()close()

您如何做到这一点对我来说似乎很奇怪。 为什么不编写一种将字符串输入然后将其写入文件的方法? 这样的事情应该可以正常工作

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM