import java.io.*;
public class Demo{
public static void main(String[] args){
File f = new File("abc.txt") ;
try{
System.setOut(new PrintStream( new FileOutputStream(f) ) ) ;
}
catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage()) ;
}
System.out.println("Hello\n") ;
try{
//throwing exception,
//is there any method to close the f File,
//before we try to open the file referred by f.
Process p = Runtime.getRuntime().exec(f.getPath()) ;
}
catch(IOException io){
System.out.println(io.getMessage()) ;
}
}
}
and the content of abc.txt after executing Demo is:-
Hello
Cannot run program "abc.txt": CreateProcess error=32, The process cannot access the file because it is being used by another process
how to avoid the exception.....
as many people here suggested, i have tried the following code, but sadly, even that is also throwing excption....:-(
import java.io.*;
class Demo{
public static void main(String[] args){
File f = new File("abc.txt") ;
FileOutputStream fos = null ;
try{
fos = new FileOutputStream(f) ;
}
catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage()) ;
}
PrintStream ps = new PrintStream(fos) ;
ps.println("Hello") ;
try{
fos.close() ;
//throwing exception again
Process p = Runtime.getRuntime().exec(f.getAbsolutePath()) ;
}
catch(IOException io){
System.out.println(io.getMessage()) ;
}
}
}
??????????