This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Output to a file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Output to a file" Watch "Output to a file" New topic
Author

Output to a file

Douggie Fox
Greenhorn

Joined: Jun 14, 2001
Posts: 19
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

Joined: Jan 09, 2001
Posts: 1492
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Output to a file
 
Similar Threads
static synchronized method
some problems regd threads as in velmurugan's notes
Cancelling Timer and TimerTasks
I Cannot Get My Thread Program Compiled
setPriority not working as expected