Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Output to a file

 
Douggie Fox
Greenhorn
Posts: 19
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I'm trying to substitute System.out.println("Something") with a command that'll print to a test file.
This is what I've been trying:
import java.io.*;
class PrintToAFile {
public static void main (String args[]) {
try {
FileOutputStream fout = new FileOutputStream("test.out");
PrintStream myOutput = new PrintStream(fout);
myOutput.println("Hello There!");
}
catch (IOException e) {
System.out.println("Error opening file: " + e);
System.exit(1);
}
}
}

And this works ok.
However, I'm also playing around with threads and I'm just getting in a mess. How do I safely output to a file in the following code ie how do I replace the System.out.println() commands?
class BasicThread extends Thread {
int sleepTime ;

public BasicThread() {

this.sleepTime = 0 ;

}

public BasicThread( int sleepTime ) {

this.sleepTime = sleepTime ;
System.out.println( getName() +" " + this.sleepTime + " sleep time " ) ;

}
public void run() {

try {
System.out.println( getName() + " going to sleep" ) ;
sleep( sleepTime ) ;
System.out.println( getName() + " waking up" ) ;
}

catch ( InterruptedException e ) {}

System.out.println( getName() + " finished" ) ;
}
}

class TryBasicThread {

public static void main( String args[] ) {

BasicThread thread1 = new BasicThread( (int)(Math.random() * 5000) ) ;
BasicThread thread2 = new BasicThread( (int)(Math.random() * 5000) ) ;
BasicThread thread3 = new BasicThread( (int)(Math.random() * 5000) ) ;
BasicThread thread4 = new BasicThread( (int)(Math.random() * 5000) ) ;
BasicThread thread5 = new BasicThread( (int)(Math.random() * 5000) ) ;

thread1.start() ;
thread2.start() ;
thread3.start() ;
thread4.start() ;
thread5.start() ;
}
}
Regards
Paul
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Paul,
Thread safety falls to synchronization. You would need to create a method inside your PrintToAFile class that is synchronized and writes to the file.
Regards,
Manfred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic