I’ve been having issues with a Java File. It's designed to write line after line in a test file as a log. Unfortunately it overwrites the same line every time I call it.
If anyone can help I would be eternally grateful as this has been driving me up the wall!
Code Below.
public abstract class Log {
protected static String DefaultLogFileLocation = "c:\\LOG.txt";
public static void ToFile(String pInputString) {
FileOutputStream pOUTPUT;
PrintStream pPRINT;
try
{
pOUTPUT = new FileOutputStream(DefaultLogFileLocation);
pPRINT = new PrintStream(pOUTPUT);
pPRINT.println (pInputString + "\n");
pPRINT.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}
}
You forgot to pass constructor parameter to specify you need to append data to file.
pOUTPUT = new FileOutputStream(DefaultLogFileLocation, true);
Also, why you don't use some Java Logging Framework? E.g. java.util.logging or log4j
Example of log4j configuration to write to file:
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="file" value="C:\\LOG.TXT" />
<param name="datePattern" value="'.'yyyy-MM" />
<param name="append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %C{6} (%F:%L) - %m%n"/>
</layout>
</appender>
<root>
<priority value ="debug" />
<appender-ref ref="FILE" />
<appender-ref ref="console" />
</root>