tags:

views:

286

answers:

5
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()) ;
     } 
    }
}

??????????

A: 

Close the FileOutputStream (or PrintStream) before you try to execute it.

David Johnstone
+1  A: 

Close the file before executing it (and don't redirect System.out):

f = new File("abc.txt");
FileOutputStream fos = new FileOutputStream(f);

// You would likely use fos.write instead, but here we go
PrintStream ps = new PrintStream(fos);
ps.println("Hello\n");

fos.close();

Process p = Runtime.getRuntime().exec(f.getPath());
phihag
actually, i want my application to display compilation status in a file (instead of displaying on command prompt), and right after thefile is created, i want to open the file programatically, so i can take a look at the compilation status....
rits
i have tried your code, but even that's not working....1 more question...if i wana show u, what code i have tried,where to post reply, because this comment-box doesn't support code-formatting...:-)
rits
you can edit your original post with the new code sample
akf
A: 
  1. What your program has created is a text file, not an executable file. An executable file is a binary file (or in some cases a script with a special header) which the operating system knows how to execute. I'm not sure what you expect should happen when you execute a text file whose contents are "Hello\n".

  2. You are redirecting stdout (standard out) to your file. Later, you printed the exception stack trace to stdout, which is why the trace appears in your file. It would probably make more sense for you to write to the file directly, instead of redirecting stdout.

JimN
but trace occurs in the catch block, and i am opening the file using exec in try block which definately executes before catch....
rits
You can close the FileOutputStream instance (you'll have to save it in a variable).
JimN
i have tried your way(see edited post), but even that is also throwing exception.....
rits
+1  A: 

I am assuming that the reason for calling Runtime.getRuntime().exec(f.getPath()); is to open up the abc.txt file in a text editor. It would be better to provide complete command for opening the text editor along with the file path. I tried this with notepad.exe (windows) and it worked.

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{
                Process p = Runtime.getRuntime().exec("notepad.exe " + f.getPath()) ;
        }
        catch(IOException io){
                System.out.println(io.getMessage()) ;
        }
    }

}

Following code dynamically generates java code and uses javac to compile it

import java.io.*;

public class Demo{

    public static void main(String[] args){

        File f = new File("Abc.java") ;
        PrintWriter writer = null;
        BufferedReader reader = null;
        InputStream pStream = null;

        try{
                // Open File Stream and write code
                writer = new PrintWriter( new FileOutputStream(f) );
                String javaCode = "public class Abc { \r\n" +
                                  "public static void main(String[] args) {\r\n" +
                                  "System.out.println(\"Hello World!\");\r\n" +
                                  "}\r\n" +
                                  "}\r\n";

                writer.println(javaCode) ;
                writer.close();

                // Run Javac to compile the code
                Process p = Runtime.getRuntime().exec("javac " + f.getPath()) ;
                p.waitFor();

                // status = 0 => Process executed without errors
                //        = 1 => Process executed with errors
                int status = p.exitValue();
                if( status ==  0 )
                {
                    pStream = p.getInputStream();
                }
                else
                {
                    pStream = p.getErrorStream();
                }

                // Display the output from the process
                reader = new BufferedReader(new InputStreamReader(pStream));
                String ln = null;
                while( (ln = reader.readLine()) != null )
                {
                    System.out.println(ln);
                }
        }
        catch(Exception ex){
                System.out.println(ex.getMessage()) ;
        }
        finally{
            try{
               if( writer != null ){writer.close();}
                if( pStream != null ){pStream.close();}
                if( reader != null ){reader.close();}
            }
            catch(Exception ex){
                System.out.println(ex.getMessage()) ;
            }
        }
    }
}
Babar
thnx Babar, it's working, but can u also explain this to me:-Cannot run program "D:\shanu\java": CreateProcess error=32, The process cannot access the file because it is being used by another process
rits
Looks like you are working on some IDE like application that can compile and run the code, right ? In that case1- Instead of redirecting System.out to file stream it will be more clean if you directly use the file stream to write the code in file.2- Basically, open file stream, write all code in file and then close file stream3- Run the Javac/Java on newly created file.
Babar
agreed...but i find myself struggling to reslove thatProcess p = Runtime.getRuntime().exec("notepad.exe " + f.getPath()) ;works fine, but, Process p = Runtime.getRuntime().exec(f.getAbsolutePath()) ;throws an exception, and the logic behind the exception is not getting clear to me.
rits
also, in this case, our file is .txt, so describing notepad.exe works fine, but what if have the path of any type of file, then what we have to pass as 1st argument?
rits
If you just call p = Runtime.getRuntime().exec("abc.txt"); java throws following exception "Cannot run program "Abc.txt": CreateProcess error=193, %1 is not a valid Win32 application". This is because 'txt' files can not be executed on windows. But when "notepad.exe 'abc.txt'" is used, java can execute it because this time file being executed is an 'exe'.
Babar
To launch files with OS associated applications see Java Desktop APIhttp://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/
Babar
A: 

assuming you are running on windows, instead of

Process p = Runtime.getRuntime().exec(f.getPath());

you could use

Process p = Runtime.getRuntime().exec("start " + f.getPath());

which should choose whatever application you have associated with .txt files.

akf
i tried Runtime.getRuntime().exec("start " + f.getPath());but, it's not working
rits