Calling another java file

I have a main class ( packet.java for example) and I need to call another file (filter.java) to display a dialog box. Both files are in the same package, but all I want to do is when a button is clicked in packet.java, I want it to display the dialog box in filter.java.

example:
you have to source files with one class in each:
file1:
public class HelloWorld {
   private String helloText = null;
   public HelloWorld(String text) { // constructor
      helloText = text;
   public String getMessage() {
      return "Hello " + helloText;
}file2 (which accesses the class in file1):
public class Foo {
   public static void main(String[] args)  {
      for(int i=0; i<args.length; i++) {
         HelloWorld hello = new HelloWorld(args);
System.out.println(hello.getMessage());
if you run the app like this:
java Foo blackieul Thofthe output will be:
Hello blackieul
Hello ThofPlease specify your problem more detailed - e.g. post an exception message or the fragment of code where you don't know what to do...

Similar Messages

  • How to invoke another Java file in Java program?

    Hello all,
    Now I am building a commnity of agents that can talk in Java, I have another Java-Based dialogue system to handle the dialogue between the agents. But I don'y know how to invoke the Java dialogue system file in the agent class.
    Is there any methods can call another .java file in a Java program?
    Help!!!!!please

    Yep, vaguest of the vaguey vague vague.
    Anyhoo,
    I'm guessing you want to call a method from a different class?
    Assuming you have the "Runner" class and then "Agent1", "Agent2", etc.
    Agent1 whatever = new Agent1();

  • Calling another class file

    I am trying to write an app to that calls another class file but i keep getting this error:
    "Message.java": Error #: 300 : class Attachment not found in class Message at line 229, column 37
    And this is the code where i am getting this error:
    public final void addAttachment(Attachment attachment)
    attachments.add(attachment);
    Can someone tell me what i am doing wrong or how to fix this?
    Thank you.

    This query brings up another point that is unrelated but of interest to me. Take a look at that method, addAttachment. All it does is call add(attachment) on an object variable that's not even lexically scoped. Is there really any benefit, any savings whatsoever in readability or ease of programming etc. in having that method? As it stands, I tend to view it as an exercise in typing. I see this a lot and so I wonder if it's just a Java thing or what.

  • Trying to compile a .java file from another .java file

    Hello,
    I'm trying to compile a .java file from another .java file using Runtime.exec...
    String c[]=new String[3];
    c[0]="cmd.exe"; c[1]="/c" ; c[2]="javac Hello.java";
    Process p=Runtime.exec(c);
    If anyone can help me in atleast getting the command prompt when Runtime.exec("cmd.exe") is executed...that would be great...I tried out notepad.exe, calc, explorer instead of cmd.exe...all the commands display their respective windows..except cmd.exe...the command prompt doesnt appear...
    Please help me ASAP....
    Thanks for your help in advance...
    Regards.
    AKhila.

    try this. ur code will be compliled and will get .class file. but console won't appear. is it a must for u?
    public class Exec{
         public static void main(String a[]) throws Exception{
              String c[]=new String[3];
              c[0]="cmd.exe"; c[1]="/c" ; c[2]="javac Hello.java";
              Process p=Runtime.getRuntime().exec(c);
              // or Runtime.getRuntime().exec("javac Hello.java");

  • Button to launch another java file????

    Hi there,
    Was wondering if someone could help with the following:
    I have a button, which once clicked opens another java file, and am aving some difficulty in doing this.
    The file which has the button is:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.util.*;
    class JFrameHolidayPlannerGUI extends JFrame
         //declare the variable using in here
         private JButton exit;
         private JButton clear;
         private JTextField t;
         private JLabel employeeId;
         private JTextField t2;
         private JLabel days;
         private JButton find;
         private JMenuItem close;
         private JMenu file;
         private JMenuBar menubar;
         private JButton add;
         private JPanel panel1;
              public JFrameHolidayPlannerGUI()
              //Set the title of the frame
              super("Company Holiday Tracking System");
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Container contentPane = this.getContentPane();
              //Created a pane with four panels and null columns
              contentPane.setLayout(new GridLayout(4,0));
              JMenuBar menubar = new JMenuBar();
              setJMenuBar(menubar);
              JMenu file = new JMenu("file");
              JMenuItem open = new JMenuItem ("Open...");
              JMenuItem save = new JMenuItem("Save");
              JMenuItem close = new JMenuItem ("Close");
              JMenuItem print = new JMenuItem ("Print...");
              menubar.add(file);
              file.add(open);
              file.add(print);
              file.add(close);
              file.add(save);
              close.addActionListener(
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)// Define the action to take after user enters the name
                             //if (e.getSource() == exit)
                             System.exit(0);
              JPanel panel = new JPanel();
              panel.setLayout(new FlowLayout(FlowLayout.LEFT));
              contentPane.add(panel);
              JLabel employeeId = new JLabel("Please Enter the employeeId", JLabel.CENTER);
              final JTextField t = new JTextField(15);
              t.setToolTipText("Please Enter the employeeId");
              t.setEditable(true);
              t.setText("Enter employeeId in here");
              JButton find = new JButton("Search for a Record");
              find.setToolTipText("Click to search for an employee record");
              find.addActionListener(
                   new ActionListener()
                        public void actionPerformed (ActionEvent e)
                             System.out.println("time");
              panel.add(employeeId);
              panel.add(t);
              panel.add(find);
              contentPane.add(panel);
              JPanel p2 = new JPanel();
              p2.setLayout(new FlowLayout(FlowLayout.LEFT));
              contentPane.add(p2);
              days = new JLabel("How many days would you like?", JLabel.LEFT);
              final JTextField t2 = new JTextField(15);
              t2.setToolTipText("How manys days would you like?");
              t2.setEditable(true);
              t2.setText("Enter the numbers of days in here");
              JButton submit = new JButton ("SUBMIT");
              find.setToolTipText("Press enter to submit holiday request");
              submit.addActionListener(
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             JFrame = new JFrame();
                             frame.addWindowListener(new WindowAdapter() {
                                       public void windowClosing(WindowEvent e) {
                                            System.open();
              p2.add(days);
              p2.add(t2);
              p2.add(submit);
              contentPane.add(p2);
              JPanel panel1 = new JPanel();
              panel1.setLayout(new FlowLayout(FlowLayout.LEFT));
              contentPane.add(panel1);
              JButton save1 = new JButton("Save");
              save1.setToolTipText("Click to save");
              panel1.add(save1);
              exit = new JButton("Exit");
              exit.setToolTipText("Click to exit");
              panel1.add(exit);
              exit.addActionListener(
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)// Define the action to take after user enters the name
                             //if (e.getSource() == exit)
                             System.exit(0);
              JButton clear = new JButton("Clear");
              clear.setToolTipText("Click to clear the information");
              panel1.add(clear);
              clear.addActionListener(
                   new ActionListener()
                        public void actionPerformed(ActionEvent e)// Define the action to take after user enters the name
                             t2.setText(" ");
                             t.setText(" ");
              add = new JButton("Add");
              add.setToolTipText("Click to add an employee");
              panel1.add(add);
              this.pack();
              this.setVisible(true);
         public static void main(String[] arg)
              JFrameHolidayPlannerGUI jf = new JFrameHolidayPlannerGUI();
    and the file that needs to be opened is:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.util.*;
    class JFrameSubmitValidate extends JFrame
         private static String label = "Are you sure you want to Submit?";
              public JFrameSubmitValidate()
                   //Set the title of the frame
                   super("Vaidator");
                   this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   Container contentPane = this.getContentPane();
                   //Created a pane with four panels and null columns
                   contentPane.setLayout(new GridLayout(2,0));
                   JLabel validate = new JLabel(label);
                   JButton OK = new JButton("OK");
                   JPanel panel = new JPanel();
                   contentPane.add(validate);
                   contentPane.add(OK);
                   this.pack();
                   this.setVisible(true);
              public static void main(String[] arg)
                   JFrameSubmitValidate sv = new JFrameSubmitValidate();
    thanx for your time.
    kev.

    Similarly to this above discussion, I would like to know how to launch another java file by clicking a button "submit". Can you guys guide me based on the code i have shown below..?
    import java.awt.*;
    import java.awt.event.*;
    class MenuFrame extends Frame implements ActionListener
    Label login=new Label("Login ID :",Label.CENTER);
    TextField lname=new TextField(12);
    Label pass=new Label("Password :",Label.CENTER);
    TextField lpass=new TextField(10);
    Button submit=new Button("Submit");
    public MenuFrame(String title)
    super(title);
    setLayout(new FlowLayout());
    add(login);
    add(lname);
    add(pass);
    add(lpass);
    add(submit);
    submit.addActionListener(this);
    addWindowListener(new CloseWindow());
    public void actionPerformed(ActionEvent e)
    Object source=e.getSource();
    if(source == submit)
    lname.setText("w");
    lpass.setText("w");
    repaint();
    public static void main(String args[])
    MenuFrame m=new MenuFrame("Java Chat Application");
    m.setSize(200,200);
    m.show();
    class CloseWindow extends WindowAdapter{
    public void windowClosing(WindowEvent event){
    System.exit(0);

  • Error Calling a java file through procedure

    Create or replace procedure Javacallprocedure(asOfDate DATE)
    as language java
    name 'oracle.xx.yy.server.Creator.run(java.sql.Date)';
    Is
    Begin
    Javacallprocedure(asOfDate);
    end;
    end procedure Javacallprocedure;
    Am trying to complie the above procedure which calls a java file from this procedure.But am getting error.Please help me.

    user10285699 wrote:
    Create or replace procedure Javacallprocedure(asOfDate DATE)
    as language java
    name 'oracle.xx.yy.server.Creator.run(java.sql.Date)';
    Is
    Begin
    Javacallprocedure(asOfDate);
    end;
    end procedure Javacallprocedure;
    Am trying to complie the above procedure which calls a java file from this procedure.But am getting error.Please help me.Can't guess what error you are getting !
    Please post the error and other source codes.
    SS

  • Calling a method from another Java file.

    I think I'm doing this right, but I'm obviously going wrong somewhere.
    In order to not have one big long java file, I've created one main one to execute the program, and another to do some of the functions. I'm using eclipse, btw.
    In the main file, I have
    currentTB = getActiveTB(playerArea);If it works, it should get send the player area variable to the getActiveTB method, and store the value it returns in the currentTB variable, right?
    In the other file, I have;
    package scenes;
    public class sceneIndex {
         private TerrainBlock getActiveTB(String areaCode) {
              TerrainBlock tBlock = new TerrainBlock();
                     **DOES STUFF**
              return tBlock;
    }I have it set up so the second file is in the source folder "resources" and the package "scenes." The problem is I'm not calling it properly. I'm missing something simple, I think. The only error I'm getting is;
    The method getActiveTB(String) is undefined...
    Where am I screwing up?
    EDIT: Yeah, I'm a rookie here trying to figure it out on my own. My computer science courses, so far, conveniently all consist of just one big java file. Easier to write, sure, but not very efficient/organized.
    Message was edited by:
    SuckerPunch

    Yeah, so this is still pissing me off. I'm not sure what else to do. I've tried this a million different ways, in both eclipse and netbeans. Whatever. Here's the code, I'd love it if someone could point out the boneheaded mistake I'm making. I'm getting a little frustrated at being stuck on such a simple problem.
    Main.javaimport com.jme.app.BaseGame;
    import com.jme.input.KeyBindingManager;
    import com.jme.input.KeyInput;
    import com.jme.math.Vector3f;
    import com.jme.renderer.Camera;
    import com.jme.renderer.ColorRGBA;
    import com.jme.scene.Node;
    import com.jme.system.DisplaySystem;
    import com.jme.system.JmeException;
    import com.jme.util.Timer;
    import com.jmex.terrain.TerrainBlock;
    import resources.*;
    public class Main extends BaseGame {
         /* General Variable Declaration */
         private String scene;   // Tells application which scene to load, default loads default scene
         private int width, height, depth, freq; // Creates variables to store information
         private boolean fullscreen;             // on the user's window
         private Camera playerCam; // Defines the main camera for the player, first person view
         private Timer timer; // Creates a timer to be used for FPS calculations
         private Node currentScene; // The basis for building the scene the player is in
         private TerrainBlock currentTB; // This variable holds the current landscape
         private String playerArea = new String("initial"); // Contains the string
                                                                        // code for the scene
                                                                        // the player is in,
                                                                        // defaults to the opening scene, unless changed by
                                                                        // the player loading their game
            public static void main(String[] args) {
              /* Initializes and Starts the Applications. */
              Main app = new Main();
              app.setDialogBehaviour(ALWAYS_SHOW_PROPS_DIALOG, Main.class.getClassLoader().getResource("img/spunch.jpg"));
              app.start();
         protected void update(float interpolation) {
         protected void render(float interpolation) {
         protected void initSystem() {
               * Application initialization properties (window, camera, renderer, key
               * bindings, etc)
              // Stores variables for window properties
              width = properties.getWidth();
              height = properties.getHeight();
              depth = properties.getDepth();
              freq = properties.getFreq();
              fullscreen = properties.getFullscreen();
              // Assigns renderer and creates game window
              try {
                   display = DisplaySystem.getDisplaySystem(properties.getRenderer());
                   display.createWindow(width, height, depth, freq, fullscreen);
                   playerCam = display.getRenderer().createCamera(width, height);
              } catch (JmeException e) {
                   e.printStackTrace();
                   System.exit(1);
              // Sets background to black, should never be seen anyway
              display.getRenderer().setBackgroundColor(ColorRGBA.black);
              // Initializes the camera
              playerCam.setFrustumPerspective(45.0f, (float) width / (float) height,
                        1, 1000);
              Vector3f loc = new Vector3f(250.0f, 100.0f, 250.0f);
              Vector3f left = new Vector3f(-0.5f, 0.0f, 0.5f);
              Vector3f up = new Vector3f(0.0f, 1.0f, 0.0f);
              Vector3f dir = new Vector3f(-0.5f, 0.0f, -0.5f);
              // Moves and orients the camera
              playerCam.setFrame(loc, left, up, dir);
              // Update the camera since it has been changed
              playerCam.update();
              // Create a timer for FPS updates
              timer = Timer.getTimer();
              // Assign the camera as the primary display in the application
              display.getRenderer().setCamera(playerCam);
              // Initialize the escape key as a way to exit the program
              KeyBindingManager.getKeyBindingManager().set("exit",
                        KeyInput.KEY_ESCAPE);
         protected void initGame() {
              /* Game initialization */
              display.setTitle("Slumlords"); // Displays title in window
                    SceneIndex sIndex = new SceneIndex();
              currentTB = sIndex.getActiveTB(playerArea);
              currentScene.attachChild(currentTB);
              currentScene.updateGeometricState(0.0f, true);
              currentScene.updateRenderState();
         protected void reinit() {
         protected void cleanup() {
    }SceneIndex.javapackage resources;
    import javax.swing.ImageIcon;
    import com.jme.bounding.BoundingBox;
    import com.jme.image.Texture;
    import com.jme.math.Vector3f;
    import com.jme.scene.state.TextureState;
    import com.jme.system.DisplaySystem;
    import com.jme.util.TextureManager;
    import com.jmex.terrain.TerrainBlock;
    import com.jmex.terrain.util.MidPointHeightMap;
    import com.jmex.terrain.util.ProceduralTextureGenerator;
    public class SceneIndex {
         private DisplaySystem display;
         public TerrainBlock getActiveTB(String areaCode) {
              TerrainBlock tBlock = new TerrainBlock();
              if (areaCode == "initial") {
                   // Generates random terrain data
                   MidPointHeightMap heightMap = new MidPointHeightMap (64, 1.0f);
                   // Scale the data
                   Vector3f terrainScale = new Vector3f(4, 0.0575f, 4);
                   // Create the terrain block
                   tBlock = new TerrainBlock("Terrain", heightMap.getSize(), terrainScale, heightMap.getHeightMap(), new Vector3f(0, 0, 0), false);
                   tBlock.setModelBound(new BoundingBox());
                   tBlock.updateModelBound();
                   // Creating a blended texture based on the height map
                   ProceduralTextureGenerator pTexture = new ProceduralTextureGenerator(heightMap);
                   pTexture.addTexture(new ImageIcon(SceneIndex.class.getClassLoader().getResource("img/grass.gif")), -128, 0, 128);
                   pTexture.addTexture(new ImageIcon(SceneIndex.class.getClassLoader().getResource("img/dirt.jpg")), 0, 128, 255);
                   pTexture.addTexture(new ImageIcon(SceneIndex.class.getClassLoader().getResource("img/granite.jpg")), 128, 255, 384);
                   pTexture.createTexture(64);
                   // Assigning the texture to the terrain
                   TextureState tState = display.getRenderer().createTextureState();
                   Texture t1 = TextureManager.loadTexture(pTexture.getImageIcon().getImage(), Texture.MM_LINEAR_LINEAR, Texture.FM_LINEAR, true);
                   tState.setTexture(t1, 0);
                   tBlock.setRenderState(tState);
              return tBlock;
    }Again, I've tried this a few different ways, and I either get a "Could Not Find Symbol" error referring to the getActiveTB(playerArea); in Main, or it just says java.lang.NoClassDefFoundError: and Exception in thread "main".
    Whatever.

  • Calling another java class from a servlet

    I am trying to write a web based form handling system (for a college project)
    I have a servlet that responds to a user request for a form. I have another java program (HTMOut) that parses the xml file for the form and produces HTML output. When I call the HTMOut from the servlet it crashes the webserver (Tomcat). But if I call HTMOut from an ordinary java class it runs fine. If I call another test program from my servlet that works too.
    Any ideas?

    where does your HTMOut output? A file or a stream? I think it is better that HTMOut can output to a stream you can set externally.

  • How do you run another Java file from a master Java file?

    We're making a game in Java at school, and we need to know how we can run a Java file from another one - like inside the master Java file, we need to have a command to run game.java (something like that). Thanks!

    We're making a game in Java at school, and we need to know how we can run a Java file from another one - like inside the master Java file, we need to have a command to run game.java (something like that). Thanks!One doesn't "run a Java file", and there's no conventional definition of "master Java file". If you want to call the main() method of another class, just make sure the class is in your classpath and call the method. If you want to start up a separate JVM with that class as a process, use Runtime.exec() or similar method.
    ~

  • Could I call another java application?????

    I wanna to exec another java application in my current Java Application.Could I?????
    can U tell me how to do this????
    thanx.

    yes u can do it in two ways !
    1) if ur problem is associated with execution of different application just like running two java application simultaneously .
    then u can use this
    call runtime environment by
    Runtime run= Runtime.getRuntime();
    then execute any process using exec() method
    run.exec(command);
    here command is a simple string which is the command syntax to run java application
    e.g.
    String command="java program1" to running program1.class
    2)but if ur problem is just execute a class file which being called by another class file.
    then its so simple.
    when u click button or select any item from list an event will be generated and in event hanling u just call the constructor of ur class file or main() method.
    public void itemStateChanged(itemEvent ie)
    if(list.getSelectedItem().equals("file1.class")
    file1 f=new file1();
    or
    file1.main("xxx","yyy");
    }

  • Call a Java file from ABAP

    Hi,
    I would like your help in identifying a mechanism in calling a Java Program from an ABAP program. The requirement is that I need to pass enough parameters(possibly in a single object like a <i>table</i>) and fetch that in a Java Program residing in a jar in the J2EE engine. The possibility of this java file interpreting this incoming object and also be able to return something to ABAP which can eventually be printed on the screen needs to be known.
    I also would like to validate an assumption of mine which is that, the jar(the receipient java file) file needs to be put under the directory
    "\usr\sap\<i>SystemID</i>\<i>instancenumber</i>j2ee\deploying\lib"
    Appreciate your time and effort in helping me with this.
    Regards,
    Sam.

    i am not sure about
    I also would like to validate an assumption of mine which is that, the jar(the receipient java file) file needs to be put under the directory
    "\usr\sap\SystemID\instancenumberj2ee\deploying\lib"
    but for your case what you could do is, on the java side get developed a jsp page which will receive data and use the jar to proces and return the results as xml. once thats done.
    from abap you can use cl_http_client class to call this jsp page to pass parameters and get the processed results from jsp page.
    Raja

  • Calling another java class from a java class

    Hi Friends,
    I have a class tht works in 2 modes,depending upon which mode i am passing (gui or text) on the command line eg:
    java myclass [mode]
    I want to call this command from another java class,and i wrote this code:
    try
             Process theProcess =
                Runtime.getRuntime().exec("java myclass  "+args[0]);
          catch(IOException e)
             System.err.println("Error on exec() method");
             e.printStackTrace();
          }When i pass "gui" it works fine,but when i pass"text", the class completes and nothing shows up on the command prompt window,so can please somebody tell me how to make this work.
    Thanks

    As aniseed just pointed out, you could do something like this:
    import javax.swing.*;
    class Test extends JFrame {
         public Test(String title) {
              this.setTitle(title);
              this.pack();
              this.setSize(300, 300);
              this.setLocationRelativeTo(null);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
         public static void main(String[] argv) { new Test(argv[0]).setVisible(true); }
    public class Test2 {
         public static void main(String[] argv) {
              Test.main(argv);
    }Run it by executing this command:
    java Test2 "Title of Frame"See if that's not what you're looking for ...

  • 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);

  • 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 do I call another exe file from a Java program?

    Hi,
    I am doing a simple IDE (text editor/interpreter) for a simple programming language we are developing. It will be submitted as our project for this semester. I created an exe file (in C) which will be used as the interpreter. How do I call the interpreter from my IDE? The interpreter should run when the user clicks a button (i.e. the "Run" button). I've tried the Java Runtime class but it doesn't work. Anyone who knows how to do it?
    Thanks!

    I first tried to do a simple program that calls system commands such as dir, cd <dir>, etc.
    I do not have the exact code right now but as far as I can remember, here's what I wrote:
    class Sample{
        public static void main(String args[]) throws IOException{
           BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
           String command;
           while ((command = in.readLine()).equalsIgnoreCase("exit") == false){
              try{
                Runtime.getRuntime().exec(command);
              }catch(Exception e){
                 System.err.println("Error: " + e);
          System.exit(0);
    }

Maybe you are looking for