简体   繁体   中英

Writing a newline in a file in a Runnable thread

I would like to write a simple class to print to a file every 5 seconds.

My code is:

public class FileLoggerTask implements Runnable
{
    private PrintWriter printWriter = null;
    private boolean isActive = true;

    public FileLoggerTask(PrintWriter printWriter)
    {
        this.printWriter = printWriter;
    }

    public void run()
    {
        while(isActive)
        {
            printWriter.println("Test line");

            try
            {
                Thread.sleep(5000);
            }

            catch(InterruptedException e)
            {
                System.out.println(e);
            }
        }
    }

    void closeTask()
    {
        isActive = false;
    }
}

And in the listener of one button I write:

File file = new File("TestFile.txt");
FileWriter fileWriter = new FileWriter(file);
PrintWriter printWriter = new PrintWriter(fileWriter);
FileLoggerTask fileLoggerTask = new FileLoggerTask(printWriter);
Thread thread = new Thread(fileLoggerTask);

and in the listener of another button I write:

fileLoggerTask.closeTask();
printWriter.close();

My problem is that it writes "Test line" in my file every 5 seconds but it doesn't append any newline. I have tried adding printWriter.println() or printWriter.println("\\n") but it doesn't work and I don't know why.

Do you have some suggestions?

Thank you very much.

How do you know there is no newline? I'm asking because if you are using some text editor on windows but your code is running on Unix, you might not see them.

Have you tried printWriter.println("\\n\\r") ?

尝试这个:

String newLine = System.getProperty("line.separator");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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