How to read files on server from a java program?

Hello,
I am fairly new to JSP programming. I have an issue with reading files. I am trying to call method of a normal java file from a jsp program. The method I am trying to call does some IO operation on Files. I have the files in the same directory as my class files on server that is in WEB-INF/classes folder. In my java program, I am giving just the file name to open because the files and the classes are in the same directory. But this is not working.
What exactly should I do to read a file from a java program, that is running on the server?
Any help is appreciated.
Thanks,
Krishna

String realFilePath = application.getRealPath("/WEB-INF/myFile.txt");
File fileToOpen = new File(realFilePath);
out.println(fileToOpen.getAbsolutePath() + ": exists? " + fileToOpen.exists());in this case "application" is a reference to the ServletContext.
It is an implicit variable in a JSP. In a servlet:
ServletContext application = getServletConfig().getServletContext();

Similar Messages

  • How to display a oracle table from a java program?

    How to display a oracle table from a java program.
    Hello friends, I have written a Java program, using oracle 10g as backend.
    I want to display a oracle table as output. Im not getting how to display oracle table as a output table.. Pls help me
    Thank you

    jayanthds, you're not going to get a satisfactory
    answer to this here. it's too big a task to justbe
    quickly outlined in a forum - the reply "all youneed
    to do is to query you table and return it asJTable"
    is worthless, for example, since the solution to
    any problem can be distilled to such a
    soundbite, if need be. doesn't make the solutionany
    simpler
    essentially you're asking "how do I write adatabase
    application?". all you'll get is snippets of code
    that, when fitted together, will eventually helpyou
    do this, but you'll spend days and days comingback
    saying "right, I've done that, now what?" until
    either you or the forum gets frustrated with the
    whole affair and the process stops
    there are entire books written about this subject,
    and countless tutorials and guides on theinternet.
    you're better off going down that routehehehe.well, it's true! I used to have a manager that would outline the solution to a problem in a few lines of pseudocode, and then firmly believe that the actual solution would be just as brief and simple. shame his pseudocode included such lofty abstractions as "reformat all data"

  • How to run a openssl command from a java program

    Hi All
    Please suggest on how to run a openssl command from a java program.
    I am using this
    Runtime runtime = Runtime.getRuntime();
    runtime.exec("openssl pkcs8 -inform der -nocrypt test.der result.pem");
    This is suppose to take test.der as input and create result.pem.
    There are no errors but the file result.pem isnt created.
    Thanks in Advance

    First off is that openssl command correct? Should it be this instead:
    openssl pkcs8 -inform der -nocrypt -in test.der -out result.pem
    Try out your openssl command within a command prompt so that you know that it works ok. I think the command line you specified waits on stdin (well it does for me).
    After that.....
    runtime.exec creates a Process object. If you do this:
    Process openssl = runtime.exec("....")
    then you can examine the return code from openssl to see the exit code - for instance if the input file does not exist then exit = 1. You can test for this with Java
    Alternatively you could get the stderr from the process and look inside it - if it is 0 length then all is good, if it has some text in there then it has likely failed. You could then throw an exception and include the stderr output in the exception messgae. You may need to experiment with this, runnig it first when openssl is happy then running it again when openssl is upset.
    M

  • How to call j2me emulator instance from a java program?

    hi,
    how to call j2me emulator instance from a java program?
    i tried public void startApp(){
    try{
    platformRequest("tel:+5550000");
    }catch(Exception e){
    e.printStackTrace();
    from a j2me midlet itself,
    but it gave illegal access exception.
    do i need any hardware phone connected to my pc?
    please help.

    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    import java.util.*;
    public class OpenExplorer{
    public static void main(String args[]){
         new OpenExplorer();
    public OpenExplorer(){
         try{
         String command = "explorer C:";
         // or String command = "cmd /c explorer C:";
         Runtime runtime = Runtime.getRuntime();
         Process process = runtime.exec(command);
         int exitVal = process.waitFor();
         System.out.println("Exit Value: " + exitVal);
         } catch(Exception e){
         e.printStackTrace();
    }

  • How to run a cygwin.bat from a java program?

    Can you please let me know how to run a cygwin.bat file from a java program and to give commands through java program. I have a program to run .exe files, but when I do the same for the cygwin.bat it doesnt work. In task mgr a BASH and a cmd.exe is running. Please help me on this & bit urgent. Thanks in advance!

    Can you please let me know how to run a cygwin.bat
    file from a java program and to give commands through
    java program. I have a program to run .exe files, but
    when I do the same for the cygwin.bat it doesnt work.Of course not. .bat files are no native executables. You need to open a shell first, like "cmd /c cygwin.bat ..."
    & bit urgent. Thanks in advance!If I had read this earlier I wouldn't have replied. Why exactly is your time worth more than anybody else's?

  • How can I pass system commands from a java program? Urgent!

    hi,
    I have been trying this out since a long time. How do I send system commands to command.com or cmd.exe from a java program and an output of the executed command back to the java application.
    If u have any idea, or have any information about the kind os application reply back.
    Thanks
    Deepa Datar

    This is the code which I tried, but it displays only the title of MS-DOS, something like " Microsoft Corp...etc ". But doesn't take any input, and the subprocess(cmd.exe) hangs.
    import java.io.*;
    public class cmddemo2
    public static void main(String arg[])
    try
    System.out.println("cmd");
    Process p=Runtime.getRuntime().exec("cmd.exe");
    DataInputStream din=new DataInputStream(p.getInputStream());
    DataOutputStream dout=new DataOutputStream(p.getOutputStream());
    System.out.println("after streams");
    String s;
    dout.writeChars("type cmddemo2.java");
    while((s=din.readLine())!="\n")
    System.out.println(s);
    dout.writeChars("dir");
    String s1;
    while((s1=din.readLine())!="\n")
    System.out.println(s1);
    System.out.println("over");
    catch(Exception e)
    { System.out.println("Exception : "+e);

  • How to list all OS processes from a java program

    I want to list/kill all OS processes from a java program, or a part from all processes according to a filter on a name of process.
    a similar functionality is ps in Unix or taskkill in Windows XP.
    Thanks!

    Hi,
    I was looking for such lib, but finally I decided to accomplish the job with my fingers end ;-). It maigh be helful for u guys:
    // is written for x based OSs
    private static void killProcess(Process process) {
    if (process == null)
    return;
    process.destroy();
    private static void closeProcessStreams(Process process) {
    try {
    process.getErrorStream().close();
    } catch (IOException eyeOhEx) {
    private static void listPHPs() {
    Process proc = null;
    Runtime rt = Runtime.getRuntime();
    int exitVal = 0;
    try {     
    proc = rt.exec(" ps -C php"); // here use ur filter. issue "man ps" in linux for more info
    catch (Exception ex) {
    System.out.println(ex.getMessage());
    killProcess(proc);
    return;
    try {
    // process the return list of ur command
    InputStream stdReturnStr = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdReturnStr);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    String returnMsg = "";
    boolean firstLine = true;
    int[] allPIDs = new int[100]; // finally we have an array of PIDs
    int PIDCount = 0;
    while ( (line = br.readLine()) != null) {
    if (!firstLine){ // the first line is title, ignore it
    returnMsg += line + "\n";
    String PID = line.trim().split(" ")[0];
    System.out.println(PID);
    try{
    allPIDs[PIDCount] = Integer.parseInt(PID);
    PIDCount++;
    }catch(Exception ex){           
    else
    firstLine = false;
    System.out.println(returnMsg);
    catch (Exception t) {
    System.out.println(t.getMessage());
    killProcess(proc);
    return;
    try {
    exitVal = proc.waitFor();
    catch (Exception t) {
    System.out.println(t.getMessage());
    killProcess(proc);
    return;
    closeProcessStreams(proc);
    Thats it!

  • How to open my computer window from a java program.....

    To open my computer window in win xp is simple from the start menu.
    i want to open it from a java program .
    any idea to open my computer from a java program or command prompt......

    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    import java.util.*;
    public class OpenExplorer{
    public static void main(String args[]){
         new OpenExplorer();
    public OpenExplorer(){
         try{
         String command = "explorer C:";
         // or String command = "cmd /c explorer C:";
         Runtime runtime = Runtime.getRuntime();
         Process process = runtime.exec(command);
         int exitVal = process.waitFor();
         System.out.println("Exit Value: " + exitVal);
         } catch(Exception e){
         e.printStackTrace();
    }

  • How to read file at server? URGENT

    hi,
    I got stucked to read a file which is at the server, i used this code :
    java.io.FileInputStream fis;
    String ipaddr="";
    int ch;
    try
         fis=new java.io.FileInputStream("server.ini");
         while((ch=fis.read())!=-1)
              ipaddr=ipaddr+(char)ch;
         ipaddr=ipaddr.trim();
         System.out.println(ipaddr);
    }catch(Exception e){System.out.println(e);}
    I'm getting a FileNotFound exception, where i went wrong.

    Hello hikiran.
    The server.ini file should reside in your application working directory. If it's not there, then the JVM won't find it. Otherwise you could specify an absolute path to the file, but your application will be less portable. Another choice you have is to define an environment variable which tells your app where the server.ini file resides, with the command
      java -Dmyapp.ServerIni=C\SomeFolder\server.ini myappThen you retrieve the pathname with:
       String path = System.getProperty("myapp.ServerIni");This way your app does not depend on the filesystem on which it's been installed to, because changing the command line that starts your app will be enough to have it working.
    Note: if you have to read a text file consider using the java.io.BufferedReader class which lets you to get rid of the different text file formats problems you find when you move to a unix like platform (newline characters are different).

  • How can I make a screensaver from a Java program?

    Hi!
    I've made a Java program works as a screensaver, and I've grouped all files into a jar file. How can I make a screensaver from this jar file?
    Thanks.

    check https://jdic.dev.java.net/documentation/incubator/screensaver/
    - I think it's still in development, but it's something...

  • How to submit a HTTP Request from a Java Program

    I am working on an web based application where in I need to submit the HttpRequest through a Java Program and not through browser. Moreover my intent is just to submit the HttpRequest. I donot want to wait for the response to come back. I have used the URL Connection class to do the same and I am trying to post this request. The contents of the methods that I am using are as below:-
    public void doPost(URL url, String inputXMLString) throws IOException
              //Create URLConnection based on the passed URL
              URLConnection connection = url.openConnection();
              connection.setDoOutput(true);
              connection.setDoInput(false);
              connection.setUseCaches(false);
              connection.setAllowUserInteraction(false);
              connection.setRequestProperty("Content-type", "application/x-www-form-
    urlencoded");
              //Get the Connection's output stream and write the request to it.
              PrintWriter out = new PrintWriter(connection.getOutputStream());
              out.print("&ena-request-input=" + URLEncoder.encode(inputXMLString));
              out.flush();
              out.close();
    Call to the above method does not invoke the URL I am intending to submit the request at.
    Can anybody give me the clue....................................................?

    I agree with the advice to launch a new thread to read and ignore the response. I don't think you should have to do it to make it work, but it's worth trying for two reasons:
    1) If it turns out it does make it work, well, then either you can leave it that way, or use that as a clue to help figure out how to make it work the way you want.
    2) There may be an error message there that will give you an idea why it's not working.
    When you say it's not invoking the servlet, what does that mean, and how do you know? Is it just that the final results aren't being seen? Put a bunch of logging statements in the servlet. It could be that it's getting hit, but you're corrupting the string you're building, or sending some extra junk that it can't handle. Spit out a log statement from the start of doPost, to see if it's even getting there. Then log the parameter. Enclose the output in quotes or braces or something to make sure there's not extra junk. I've had XML docs not parse because there was a blank line at the beginning.
    If it works in the browser but not from your standalone app, then you need to have the servlet tell what difference it sees in the two cases. Print out headers, other params, everything you can think of.
    Re-read the docs for URL, HttpURL, whatever, to make sure you're doing all the right steps in the right order. Make a servlet that just takes a single, simple param=value via POST and see if you can get that to work.

  • How to Create Linux-Cron Job  from a Java Program

    Hello,
    Can anybody help me to CREATE/EDIT/DELETE Linux Cron job from Java Program. Its Very Urgent.Thanks in advance..
    from
    Chakri

    I decided this didn't sound too tough so I played around with it a little. Basically because I'd never tried executing external processes out of java before, so I wanted to see how it was done.
    Just change whatever you like in the jobs ArrayList and call writeJobs.
    If you call writeJobs without putting anything in the list first you'll wipe out all of your crontab entries.
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    public class cron {
        ArrayList jobs;
        Runtime rt;
        cron() {
         rt = Runtime.getRuntime();
         jobs = new ArrayList();
        void readCron() {
         String[] list = { "crontab", "-l" };
         jobs = new ArrayList();
         try {
             // Stick a job into crontab
             Process child = rt.exec(list);
             BufferedReader cronout = new BufferedReader(new InputStreamReader(child.getInputStream()));
             String cronjob = cronout.readLine();
             while (cronjob != null) {
              jobs.add(cronjob);
              cronjob = cronout.readLine();
             child.waitFor();
         catch(IOException e) {
             System.err.println("IOException starting process!");
         catch(InterruptedException e) {
             System.err.println("Interrupted waiting for process!");
        void listJobs() {
         Iterator iter = jobs.iterator();
         while (iter.hasNext()) {
             System.out.println((String)iter.next());
        void writeJobs() {
         String[] edit = { "crontab"};
         try {
             // Stick a job into crontab
             Process child = rt.exec(edit);
             PrintWriter cronIn = new PrintWriter(child.getOutputStream());
             Iterator iter = jobs.iterator();
             while (iter.hasNext()) {
              cronIn.println((String)iter.next());
             cronIn.close();
             child.waitFor();
         catch(IOException e) {
             System.err.println("IOException starting process!");
         catch(InterruptedException e) {
             System.err.println("Interrupted waiting for process!");
        void doStuff() {
         readCron();
         listJobs();
         jobs.add("* * * * 4 cronjob");
         writeJobs();
         readCron();
         listJobs();
        public static void main(String[] args) {
         cron c = new cron();
         c.doStuff();
    }

  • Accessing Sql Server from AS400 Java program

    Hi everybody,
    I am trying to access Sql Server from an AS400 Java program. I have tried various Sql Server JDBC drivers including the Microsoft one but no luck yet. When i try to compile my Java program (with driver file in the classpath) it gives some errors on the driver jar file and also it throws out lots of unreadable text characters. This gave me a feeling that probably its a character coding issue with the jar file, so i tried ftp the file in binary mode as well as copying through the Operations Navigator. But still compilation is giving the same kind of errors.
    Do I need to have some special JDBC Drivers compiled for AS400 specifically. My understanding was that Java is platform independent so any JDBC Type 4 driver will work.
    We are running Java 1.3 on the AS400. Any help on this issue would be great.
    Thanks
    Inder

    Thanks for the help. I am writing a Java program after a long time that's why was making that mistake. Now the program gets compiled correctly but on running the program i am getting the following error message:
    java 001-0070: Exception JVAB544 not expected
    /myjava/test/msbase.jar: 001-0050 Syntax error on Line 1: token ')' not expected
    /myjava/test/msutil.jar: 001-0050 Syntax error on Line 1: token ')' not expected
    /myjava/test/mssqlserver.jar: 001-0050 Syntax error on Line 1: token ')' not expected
    I have no idea what is this error about. Though the same driver files don't give any error when running on a Windows machine.
    Thanks

  • How to display a javafx window from a java program?

    hello,
    I found in the help how to call a java class from a javafx class, but how can I do the opposite : make a javafx window visible and active from a java class (main method e.g.)?
    thank you,
    olivier.

    I haven't studied the topic, but I stumbled upon a good number of threads and blog articles on how to use JavaFX in Swing...
    Basically it is hackish (might depend on current implementation, thus break on new releases) because Sun didn't designed it for this task.

  • How can I get the events from a java program?

    I want to make a monitor to watch a java program.How can I get the events from the GUI of this program some as mouse cliking, keyinput. So I can watch these in my monitor.
    Thanks

    Hi,
    To put a monitor to the events occuring in the GHUI u need to register required components with the appropriate EventListeners.
    Liek if u want to get notified when a mouse is clicked, then u need to add The MouseListener to the component which u want to be monitored.
    Say
    myFrame which is the JFrame object which shuld be monitored for the events.
    Then in ur program u have to add following code
    myFrame.addMouseListener( someObectReference );
    Here the someObjectReference should be an instance to a concrete class ..i.e. U write a class like the following
    public class MyMouseListener implements MouseListener {
    // override the followig methods
    public void mouseClicked(MouseEvent me){ sop("MOUSE CLICKED ON THE FRAME");}
    public void mousePressed(MouseEvent me){}
    public void mouseReleased(MouseEvent me){}
    If u dont want to use another class for listening to the events. Then u can make teh current class monitor the events. To do so ur class should implement the appropriate listener and should override the required methods.
    and u should say myFrame.addMouseListenet( this );
    thats it

Maybe you are looking for