Programatically executing a seperate java file

Hey java forums! I need one of my programs to programatically run/execute a separate .java OR .class file that also has a main method. Can I and how do I do this? Thank you in advance!

Also, you may need to use a URLClassLoader if the java class file you are trying to run is not on the classpath.
You may want to set security permissions or a shutdown hook on the other app that you start so that if it calls system.exit, it doesn't shut down your main app.
Finally, you can also use Runtime.exec to start another java app. This has the advantage of not needing the shutdown hook.

Similar Messages

  • Public class must be written in a seperate .java file?

    Hi,
    1. why is it compulsory for a public class to be written in a seperate .java source file?
    2. why can not a .java source file contain more than one public classes?

    Can you elaborate more on "to make it quicker for the compiler to import packages"Think what you'd do if you were the compiler and you needed to handle this code :
    package my;
    import my.gaphics.*;
    import my.util.*;
    class My {
      private Utility x;
    }How do you work out where to look for the source of class Utility? If you insist that all public classes are declared in a file with the matching name then you only need to check whether my/graphics/Utility.java or my/util/Utility.java exists, and there you have your source. Otherwise you'd need to parse all imported packages upfornt, since you can't tell which file will contain the source of Utility.

  • Error Encounterd while executing the Custom java file

    Hi,
    I have created a Custom Java file namely TestClient.java,if I try to run this file I get the following error:-
    java.lang.NoSuchMethodError: oracle.xml.parser.v2.SAXParser.setContentHandler(Lorg/xml/sax/ContentHandler;)V      at oracle.jdeveloper.cm.DefaultConnectionStore.read(DefaultConnectionStore.java:182)      at oracle.jdeveloper.cm.ConnectionManager.loadConnectionDescriptors(ConnectionManager.java:1223)      at oracle.jdeveloper.cm.ConnectionManager.getConnectionDescriptorImpl(ConnectionManager.java:1203)      at oracle.jdeveloper.cm.ConnectionManager.putConnectionDescriptor(ConnectionManager.java:336)      at oracle.jbo.client.Configuration.registerConnectionsFromDocument(Configuration.java:1029)      at oracle.jbo.client.Configuration.loadFromStream(Configuration.java:262)      at oracle.jbo.client.Configuration.loadFromClassPath(Configuration.java:350)      at oracle.jbo.common.ampool.PoolMgr.createPool(PoolMgr.java:272)      at oracle.jbo.common.ampool.PoolMgr.findPool(PoolMgr.java:473)      at oracle.jbo.client.Configuration.createRootApplicationModule(Configuration.java:1286)      at oracle.jbo.client.Configuration.createRootApplicationModule(Configuration.java:1264)      at Package6Module.TestClient.main(TestClient.java:20)
    Any Idea?Where am I going wrong ?The code that I have wriiten is as below :
    package package6.Package6Module;
    import oracle.jbo.*;
    import oracle.jbo.domain.Number;
    import oracle.jbo.client.Configuration;
    public class TestClient
    public TestClient()
    public static void main(String[] args)
    String _cf = "Package6ModuleLocal";     // Configuration Name
    String _am = "package6.Package6Module.Package6Module"; // Application Module Name
    // Create an instance of the appmodule by name, using Local mode
    ApplicationModule am_Ord = Configuration.createRootApplicationModule(_am,_cf);
    // Find the "CustomerView" view object by name in the app module
    ViewObject vo_Dept = am_Ord.findViewObject("GecmRpScheduleLinesTestView");
    System.out.println("AM_Module :"+am_Ord);
    }

    BI Publisher

  • Compiling / Running a Java file in JSP

    Hi,
    ok, I have a jsp page, which we will call page 1. Once I go to that page, I all I want it to do is compile a certain file.java, and then run the file.java. The user doesn't actually know that this is going on in the background. Page 1 automatically redirects the user to page 2 (also a jsp page).
    The java program that I created (that was previously compiled and ran) creates a special javascript file. After running the file.java in page #1, the java file creates a javascript file that will be used in page 2 to display a tree node (group of information).
    so, right now, I'm trying to figure out how to write the jsp code that will tell how to compile and run a java file. I was thinking about using javabeans before, but I think you HAVE to actually display the contents of the java file into the jsp (I think). Anyhow, thanks for the help!

    sorry about being ambiguous before. What I mean by
    running a java file was that I already created a java
    file. I don't want to hava my java statements inside
    the jsp file. I just want the jsp file have a command
    in it that would call a java file, tell the java file
    to compile and run. All the jsp file would do
    (hopefully) is just give commands for a seperate java
    file to compile and run. Thanks again for any help!Ok, so this other java file has some entry-point method, like main(), right? So call it...
    <%
    YourJavaClass.main(appropriateArgumentsGoHere);
    %>
    or better yet, it's an object you can use:
    <%
    YourJavaClass x = new YourJavaClass();
    x.callSomeMethodHere(withAppropriateArgumentsHere);
    x.callAnotherMethodMaybe();
    %>
    You don't need the jsp file to "compile" this java file, you'd already have compiled it beforehand, and it's class bytecode needs to be in your classpath (on the server side) of course.

  • Importing java files

    Hey all,
    I created two seperate objects in two seperate java files. Now I want to "#include" them into a third java object. How is this done in java?
    Thanks,
    Wali

    If they're in the same package, nothing. If they're in different packages, use the import statement; e.g.: import path.to.yourpackage.*;

  • How can i execute "*.java " files in Workshop

    Hi,
    Im sunil,new to this weblogic workshop8.1..i dont know how to execute standalone .java files or servlets in workshop.plz help me and tell the way.
    regards
    Budati sunil

    Im not too sure about the Java project. But single normal java files with public static void maain(String [] args) are very simple to execute.
    1. Write the java code somewhere lets call this class A.
    2. Make a dummy page flow.
    3. In the begin action of this pageFlow, call the main method of the A class directly using A.main(null) since main is a static method. your code will work fine.
    4. If you have to pass a String[] as parameters. Before calling main, create this String[] and then pass it.
    In this way you can make a jsp and take the input from the user also.
    Hope it helps
    Cheeers

  • How to execute one java file in another java file

    Hi All!
    I hava a problem.. I need to validate functionality of one java file in my Junit test case.. so, I need to run that java file in my test file..
    How should I start with???? Are there any java API's for that.. I checked 'system' ..but which function will suite that functionality,,I am not sure about..

    I need to check the functionality of deletetion which
    is done by a java class.. Now I need to check this
    functionality..whether it is deleting or not... in my
    test case.. so, for that I need to execute that java
    file in similar manner as how we normally do it...,
    in my test case..So let the test case create a file and have your class delete it. What's there to run?

  • How to use schedule task for execute my java file

    I have five java file.
    I want every 20 minutes all of them executed.
    how to write the program for scheduling that execution.

    > I have five java file.
    I want every 20 minutes all of them executed.
    how to write the program for scheduling that
    execution.
    I recommend using an external application (e.g., Task Scheduler, cron, etc.) to handle this kind of scheduling.
    ~

  • How to get "Executable java file"?

    Hi,
    I wanted to get the .class file of my java programme for execution. i.e say "c:\java Abc ", I wanted to get "Abc" so that I can execute my file in my GUI like "java Abc".
    Here is what I am doing
    File file;
    String command = "java";
    Process p;
    String classname = file.getPath(),fileName = file.getName();
    p = Runtime.getRuntime().exec(command+" "+classname);
    When I use this, I get the .java file. I wanted to get the "EXECUTABLE FILE ONLY", can any one help me?
    Thanks

    Put these lines after fileName = file.getName();
    if (fileName.endsWith(".java"))
        // Remove the .java extension from the filename
        fileName = fileName.substring(0, fileName.length() - 5);
    }

  • .java files compile but cannot execute

    Hello,-
    I have a small problem in that the compiler can find the .java file (javac javaFile.java), however the execute command (java javaFile) does not work (Exception in thread "main" java.lang.NoClassDefFoundError: javaFile). I'm using Windows Vista and JDK 1.6.0_02. Which one of the environment variables is responsible for file execution?
    Thanks beforehand, Vahagn

    @ smithberry: Now it executes! Thanks for pointing that out and apologies for not seeing the space before the filename. But how come this is at all necessary? Do I have to run all my java programs with this command from now on, including the JUnit TestCase extensions?

  • Cannot Execute .java File..

    Hi,i'm really confused about this..it's so weird..
    i'm trying to execute (.java) file from another directory, but
    it can't,why? if i just compile that file from another directory
    there's no problem with that...
    ex : i have file named Hello.java which i save it on C:\Work
    i compile this file like this :
         C:\javac C:\Work\Hello.java
    there's no problem when i compile that file, but when i try to
    execute that file i got this messages :
    Exception in thread "main" java.lang.NoClassDefFoundError: C:\Work\Hello
    this is how i execute that file : C:\java C:\Work\Hello
    if i execute like this : C:\Work\java Hello, there's no problem..
    Why (.java) file cannot be execute from another directory...
    Thanks a lot..

    It considers the pathname to be part of the class name when you do it like that, and since you don't have a class named C:\Work\Hello (and can't, since you can't use colons or backslashes in the name), that's not gonna happen.
    Try this:
    java -classpath C:\Work\ Hello
    Note the space between C:\Work\ and Hello. Hope that helps :)

  • .java file compiling but not executing in jdk6

    Using javac in jdk6 I can compile a .java file but cant executing the same using java command from my own directory. I can still compile and execute the same file from jdk\bin directory. I am using windows XP Home. While executing the .java file from my own directory, it fires a message: "The Java class could not be loaded. java.lang.UnsupportedClassVersionError: Myfilename (Unsupported major.minor Version 50.0)". i have set path in environment variable as "C:\sun\sdk\jdk\bin" where jdk placed in sun\sdk.
    Please help me to solve the problem

    This isn't information we can give you. You have to set it up based on your system.
    Do you understand how execution paths work? There's a list of filesystem paths, separated by a semicolon or a colon depending on the system, all concatenated into one big string. The entries earlier in the string are looked in first.
    So if your path has this:
    c:\Windows\java;c:\sun\sdk\jdk\bin
    Then if you type "java" from the command line, the Windows one would be executed, not the JDK 6 one.

  • JSP executing .java file

    Hi,
    I have a small and simple question about JSP: can it either:
    - compile a .java file and then execute (or interpret) the bytecode created ?
    - execute a .class file ?
    Thank you

    ok nevermind,
    found a good tutorial about this.
    cheers

  • Using java class and variables declared in java file in jsp

    hi everyone
    i m trying to seperate business logic form web layer. i don't know i am doing in a right way or not.
    i wanted to access my own java class and its variables in jsp.
    for this i created java file like this
    package ris;
    import java.sql.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class  NewClass{
        public static void main(String args[]){
            Connection con = null;
            ResultSet rs=null;
            Statement smt=null;
            try{
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                con=DriverManager.getConnection("jdbc:mysql:///net","root", "anthony111");
                smt=con.createStatement();
               rs= smt.executeQuery("SELECT * FROM emp");
               while(rs.next()){
                String  str = rs.getString("Name");
                }catch( Exception e){
                    String msg="Exception:"+e.getMessage();
                }finally {
          try {
            if(con != null)
              con.close();
          } catch(SQLException e) {}
    }next i created a jsp where i want to access String str defined in java class above.
    <%--
        Document   : fisrt
        Created on : Jul 25, 2009, 3:00:38 PM
        Author     : REiSHI
    --%>
    <%@page import="ris.NewClass"%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
        </head>
        <body>
            <h1><%=str%></h1>
        </body>
    </html>I wanted to print the name field extracted from database by ResultSet.
    but it gives error cannot find symbol str.
    please help me to find right way to do this.
    i am using netbeans ide.

    Very bad approach
    1) Think if your table contains more than one NAMEs then you will get only the last one with your code.
    2) Your String is declared as local variable in the method.
    3) You have not created any object of NewClass nor called the method in JSP page. Then who will call the method to run sql?
    4) Your NewClass contains main method which will not work in web application, it's not standalone desktop application so remove main.
    Better create an ArrayList and then call the method of NewClass and then store the data into ArrayList and return the ArrayList.
    It should look like
    {code:java}
    package ris;
    import java.sql.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class  NewClass{
        public static ArrayList getNames(){
            Connection con = null;
            ResultSet rs=null;
            Statement smt=null;
            ArrayList nameList = new ArrayList();
            try{
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                con=DriverManager.getConnection("jdbc:mysql:///net","root", "anthony111");
                smt=con.createStatement();
               rs= smt.executeQuery("SELECT * FROM emp");
               while(rs.next()){
                nameList.add(rs.getString("Name"));
               return nameList;
                }catch( Exception e){
                    String msg="Exception:"+e.getMessage();
                   </code><code class="jive-code jive-java"><font>return nameList;</code><code class="jive-code jive-java">
                }finally {
          try {
            if(con != null)
              con.close();
          } catch(SQLException e) {}
          </code><code>return nameList;</code>
    <code class="jive-code jive-java">    }

  • How to pass the value of variable to another java file?

    Hi. I have 2 java files (LogonAction.java and PCAction.java). The value of variable(String getrole) depends on the logon user. How can I use this value of variable in PCAction.java? I want to execute a sql statement in PCAction.java which is (String sql="Select * from PP where role"+"='" + getrole + "'") Thanks a lot.
    LogonAction.java is below:
    package test;
    import test.jdbc.util.ConnectionPool;
    import java.sql.*
    import java.util.*;
    import javax.servlet.http.*;
    import org.apache.commons.logging.*;
    import org.apache.struts.action.*;
    import org.apache.struts.util.*;
    import org.apache.commons.beanutils.PropertyUtils;
    public final class LogonAction extends Action {
    private Log log = LogFactory.getLog("org.apache.struts.webapp.Example");
    private ConnectionPool pool;
    public LogonAction() {
    pool = ConnectionPool.getInstance();
    public String getrole;
    public ActionForward execute(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws Exception {
    Locale locale = getLocale(request);
    MessageResources messages = getResources(request);
    ActionErrors errors = new ActionErrors();
    String username = (String)PropertyUtils.getSimpleProperty(form, "username");
    String password = (String)PropertyUtils.getSimpleProperty(form, "password");
    String getusername=CheckUser(username,password);
    getrole=getusername;
    java.lang.System.out.println(getrole);
    if ("".equals(getusername))
    errors.add(ActionErrors.GLOBAL_ERROR,
    new ActionError("error.password.mismatch"));
    getusername=username+getusername;
    // Report any errors we have discovered back to the original form
    if (!errors.isEmpty()) {
    saveErrors(request, errors);
    return (mapping.getInputForward());
    // Save our logged-in user in the session
    HttpSession session = request.getSession();
    session.setAttribute(Constants.USER_KEY, getusername);
    if (log.isDebugEnabled()) {
    log.debug("LogonAction: User '" + username +
    "' logged on in session " + session.getId());
    // Remove the obsolete form bean
    if (mapping.getAttribute() != null) {
    if ("request".equals(mapping.getScope()))
    request.removeAttribute(mapping.getAttribute());
    else
    session.removeAttribute(mapping.getAttribute());
    // Forward control to the specified success URI
    return (mapping.findForward("success"));
    * Look up the user, throwing an exception to simulate business logic
    * rule exceptions.
    * @param database Database in which to look up the user
    * @param username Username specified on the logon form
    * @exception ModuleException if a business logic rule is violated
    public String CheckUser(String username,String password){
    Connection con = null;
    try
    con = pool.getConnection();
    String sql = "SELECT * from user WHERE userid = ? AND password= ?";
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
    if (con.isClosed()) {
    throw new IllegalStateException("error.con.isClosed");
    ps = con.prepareStatement(sql);
    ps.setString(1,username);
    ps.setString(2,password);
    rs = ps.executeQuery();
    String returnstr="";
    while(rs.next())
    returnstr=rs.getString("role");
    java.lang.System.out.println(returnstr);
    return returnstr;
    } catch (SQLException e) {
    e.printStackTrace();
    throw new RuntimeException("error.ps.executeQuery");
    } finally {
    try {
    if (ps != null)
    ps.close();
    if (rs != null)
    rs.close();
    } catch (SQLException e) {
    e.printStackTrace();
    throw new RuntimeException("error.rs.close");
    catch (SQLException e)
    e.printStackTrace();
    throw new RuntimeException("Unable to get connection.");
    finally
    try
    if (con != null)
    con.close();
    catch (SQLException e)
    throw new RuntimeException(e.getMessage());
    }

    You can use PreparedStatement and
    String cmd = "select * from PP where role=?";
    PreparedStatement stmt = conn.prepareStatement(cmd);
    stmt.setString(1,theRole);

Maybe you are looking for

  • How To Retrieve an Object's Value Defined Using c:set ... Tag?

    I have the value of a variable defined in JSP#1 (JSP#1 is not a form) using JSTL tag:    <c:set var="id" value="${articleForm.article}" scope="session"/>Now, I have an object 'id' in the session scope. The object 'id' and all the information, which a

  • Deploy OpenStack GA release failed due to anti-affinity rule

    When I deploy the OpenStack GA release, following error popped up at the last step on the deployment wizard page. "Deploy OpenStack instance failed. Insufficient number of ESXi hosts to meet the anti-affinity rule" I have 3 ESXi hosts in management c

  • How do I get back the volume control in internet plugin

    In Safari 4, when I play some items like the quicktime trailers from Apple's site, I see a volume control under the movie, and clicking it brings up the slider as expected. However in most other items Quicktime wants to play (e.g. an mp3 like http://

  • FM HR_READ_INFOTYPE to read records from 3 infotypes

    Hi all, I am writing a report using PNP as my LDB. So there is a selection screen which can takes in the pernr and the dates as begda and endda. Based on this scenario, how do you normally use this FM 'HR_READ_INFOTYPE' to all the records from let sa

  • Selecting Printer defined in VV22 Transaction for Smartform printout

    Hi All, Can any one help me. My requirement is to print a picking list output using smartform automatically when ever a transfer order is generated. The main problem is i have to select the printer which is defined in VV22 Transaction for that partic