views:

86

answers:

3

I’ve been having issues with a Java File.

Its 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. Thanks.

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");
}
}
}
}
+1  A: 

Try using pOUTPUT = new FileOutputStream(DefaultLogFileLocation, true);. [Javadoc][1] here.

[1]: http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File, boolean)

Teja Kantamneni
+2  A: 

I suggest using the FileOutputStream constructor that has an append parameter.

Generally, get familiar with the Javadocs, they can answer simple questions like that much more quickly than people here.

Michael Borgwardt
+4  A: 

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/"&gt;
  <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>

uthark
+1 for suggesting using an existing logging framework.
Mark Peters