繁体   English   中英

执行一个动态创建的文件

[英]executing a dynamically created file

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

}

执行Demo后abc.txt的内容为:-

你好

无法运行程序“abc.txt”:CreateProcess error=32,该进程无法访问该文件,因为它正被另一个进程使用

如何避免异常......

正如这里的许多人所建议的那样,我已经尝试了以下代码,但遗憾的是,即使那样也会抛出 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()) ;
        } 
    }
}

??????????

我假设调用 Runtime.getRuntime().exec(f.getPath()); 的原因是在文本编辑器中打开 abc.txt 文件。 最好提供打开文本编辑器的完整命令以及文件路径。 我用 notepad.exe (windows) 试过了,它成功了。

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

}

下面代码动态生成java代码,使用javac编译

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

在执行之前关闭文件(并且不要重定向 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());

在尝试执行之前关闭FileOutputStream (或PrintStream )。

  1. 您的程序创建的是文本文件,而不是可执行文件。 可执行文件是操作系统知道如何执行的二进制文件(或者在某些情况下是带有特殊标头的脚本)。 当您执行内容为“Hello\n”的文本文件时,我不确定您期望发生什么。

  2. 您正在将标准输出(标准输出)重定向到您的文件。 后来,您将异常堆栈跟踪打印到标准输出,这就是跟踪出现在您的文件中的原因。 直接写入文件而不是重定向 stdout 可能更有意义。

假设您在 windows 上运行,而不是

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

你可以使用

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

它应该选择与.txt 文件关联的任何应用程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM