Inputstream.....help me...

Hi guys,
i've a question for you.
My Jsf Application allow user to upload a txt file thanks to a Myfaces
component.
I want manipulate later this file and i know that exist getInputStream
function that allow it.
My question is that i have to add to my application a java class that
does some operations on the file that i have uploaded.
The matter is that my application load a file in a bufferedReader with
BufferedReader br = new BufferedReader(file);
How can i put the inputstream of my uploaded file in the bufferedReader
to reuse my java application?
Please help me,i'm a newbie..excuse me for my english

Use FileInputStream

Similar Messages

  • Parse XML in inputstream, help!

    From a socket, I get a XML from the inputstream, in the XML it has many tages called "City", I want to take all the Citys out and put them in an array, there is something with my code, who can fix it?
    import java.io.*;
    import java.net.*;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    public class TCPClient { 
    public static void main(String argv[])throws Exception { 
    final int HTTP_PORT=80;
    Socket socket1 = new Socket("www.webservicex.net", HTTP_PORT);
    BufferedWriter out= new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream(), "UTF8"));
    // BufferedReader in= new BufferedReader(new InputStreamReader(socket1.getInputStream()));
    out.write("POST http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry HTTP/1.0\r\n");
    out.write("Host: www.webservicex.net\r\n");
    out.write("Content-Type: application/x-www-form-urlencoded\r\n");
    String body = "CountryName=china";
    out.write("Content-Length: " + body.length() + "\r\n");
    out.write("\r\n");
    out.write(body);
    out.flush();
         InputStreamReader inputStream = new InputStreamReader(socket1.getInputStream());
              System.out.println("Encoding is " + inputStream.getEncoding());
              BufferedReader in = new BufferedReader(inputStream);
    String xmlString="";
    String line;
    while((line=in.readLine())!=null){
         xmlString+=line;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new InputSource(new StringReader(xmlString)));
    NodeList nl = document.getElementsByTagName("City");
    for (int count = 0; count < nl.getLength(); count++) {  
    Node n = nl.item(count);
    System.out.println(n);
    out.close();
    in.close();
    }

    There are no "City" elements in the XML. In fact, as with your post yesterday, there is very very little in the XML.
    Also, there is no need to create a String of the response. You can use the reader directly to in the InputSource.
    Edited by: sabre150 on Aug 11, 2009 1:08 PM

  • Error in feeding JMF with inputstream, please help

    Hi,
    in order to feed JMF with inputstreams, audioinputstreams actually, you have to modify the DataSource.java and write a custom one so that it accepts inputstreams for the construction of the datasource, because with MediaLocator you can only specify existing files in the hard disk or somewhere in the network.
    Searching I found this ByteBufferDataSource, which allows you to construct a DataSource from a ByteBuffer object.
    The problem is that when using it and trying to send the stream via RTP to another machine, i get the following error:
    Exception in thread "JMF thread: com.sun.media.ProcessEngine@d6a05e[ com.sun.media.ProcessEngine@d6a05e ] ( configureThread)" java.lang.NullPointerException
         at com.sun.media.ProcessEngine.isRTPFormat(ProcessEngine.java:99)
         at com.sun.media.ProcessEngine.reenableHintTracks(ProcessEngine.java:107)
         at com.sun.media.ProcessEngine.doConfigure(ProcessEngine.java:63)
         at com.sun.media.ConfigureWorkThread.process(BasicController.java:1370)
         at com.sun.media.StateTransitionWorkThread.run(BasicController.java:1339)
    This error has appeared in some other post, but haven�t found the solution to it, I guess is something to do with the file format.
    So please, I really need your help with this, as I�m getting stuck in a academical project because of this. I attach the bytebufferdatasource
    Thank you for your time,
    bye
    import javax.media.protocol.ContentDescriptor;
    import javax.media.protocol.PullDataSource;
    import java.nio.ByteBuffer;
    import java.io.IOException;
    import javax.media.MediaLocator;
    import javax.media.Duration;
    import javax.media.Time;
    * @author Chad McMillan
    public class ByteBufferDataSource extends PullDataSource {
    protected ContentDescriptor contentType;
    protected SeekableStream[] sources;
    protected boolean connected;
    protected ByteBuffer anInput;
    protected ByteBufferDataSource(){
    * Construct a <CODE>ByteBufferDataSource</CODE> from a <CODE>ByteBuffer</CODE>.
    * @param source The <CODE>ByteBuffer</CODE> that is used to create the
    * the <CODE>DataSource</CODE>.
    public ByteBufferDataSource(ByteBuffer input, String contentType) throws IOException {
    anInput = input;
    this.contentType = new ContentDescriptor(contentType);
    connected = false;
    * Open a connection to the source described by
    * the <CODE>ByteBuffer/CODE>.
    * <p>
    * The <CODE>connect</CODE> method initiates communication with the source.
    * @exception IOException Thrown if there are IO problems
    * when <CODE>connect</CODE> is called.
    public void connect() throws java.io.IOException {
    connected = true;
    sources = new SeekableStream [1];
    sources[0] = new SeekableStream(anInput);
    * Close the connection to the source described by the locator.
    * <p>
    * The <CODE>disconnect</CODE> method frees resources used to maintain a
    * connection to the source.
    * If no resources are in use, <CODE>disconnect</CODE> is ignored.
    * If <CODE>stop</CODE> hasn't already been called,
    * calling <CODE>disconnect</CODE> implies a stop.
    public void disconnect() {
    if(connected) {
    sources[0].close();
    connected = false;
    * Get a string that describes the content-type of the media
    * that the source is providing.
    * <p>
    * It is an error to call <CODE>getContentType</CODE> if the source is
    * not connected.
    * @return The name that describes the media content.
    public String getContentType() {
    if( !connected) {
    throw new java.lang.Error("Source is unconnected.");
    return contentType.getContentType();
    public Object getControl(String str) {
    return null;
    public Object[] getControls() {
    return new Object[0];
    public javax.media.Time getDuration() {
    return Duration.DURATION_UNKNOWN;
    * Get the collection of streams that this source
    * manages. The collection of streams is entirely
    * content dependent. The MIME type of this
    * <CODE>DataSource</CODE> provides the only indication of
    * what streams can be available on this connection.
    * @return The collection of streams for this source.
    public javax.media.protocol.PullSourceStream[] getStreams() {
    if( !connected) {
    throw new java.lang.Error("Source is unconnected.");
    return sources;
    * Initiate data-transfer. The <CODE>start</CODE> method must be
    * called before data is available.
    *(You must call <CODE>connect</CODE> before calling <CODE>start</CODE>.)
    * @exception IOException Thrown if there are IO problems with the source
    * when <CODE>start</CODE> is called.
    public void start() throws IOException {
    * Stop the data-transfer.
    * If the source has not been connected and started,
    * <CODE>stop</CODE> does nothing.
    public void stop() throws IOException {
    }

    Sorry for the formatting, I attach it again here with well format:
    the error was:
    Exception in thread "JMF thread: com.sun.media.ProcessEngine@d6a05e[ com.sun.media.ProcessEngine@d6a05e ] ( configureThread)" java.lang.NullPointerException
         at com.sun.media.ProcessEngine.isRTPFormat(ProcessEngine.java:99)
         at com.sun.media.ProcessEngine.reenableHintTracks(ProcessEngine.java:107)
         at com.sun.media.ProcessEngine.doConfigure(ProcessEngine.java:63)
         at com.sun.media.ConfigureWorkThread.process(BasicController.java:1370)
         at com.sun.media.StateTransitionWorkThread.run(BasicController.java:1339)
    and the java file for generating the datasource from the bytebuffer was:
    import javax.media.protocol.ContentDescriptor;
    import javax.media.protocol.PullDataSource;
    import java.nio.ByteBuffer;
    import java.io.IOException;
    import javax.media.MediaLocator;
    import javax.media.Duration;
    import javax.media.Time;
    * @author  Chad McMillan
    public class ByteBufferDataSource extends PullDataSource {
        protected ContentDescriptor contentType;
        protected SeekableStream[] sources;
        protected boolean connected;
        protected ByteBuffer anInput;
        protected ByteBufferDataSource(){
         * Construct a <CODE>ByteBufferDataSource</CODE> from a <CODE>ByteBuffer</CODE>.
         * @param source The <CODE>ByteBuffer</CODE> that is used to create the
         * the <CODE>DataSource</CODE>.
        public ByteBufferDataSource(ByteBuffer input, String contentType) throws IOException {
            anInput = input;
            this.contentType = new ContentDescriptor(contentType);
            connected = false;
         * Open a connection to the source described by
         * the <CODE>ByteBuffer/CODE>.
         * <p>
         * The <CODE>connect</CODE> method initiates communication with the source.
         * @exception IOException Thrown if there are IO problems
         * when <CODE>connect</CODE> is called.
        public void connect() throws java.io.IOException {
            connected = true;
            sources = new SeekableStream [1];
            sources[0] = new SeekableStream(anInput);
         * Close the connection to the source described by the locator.
         * <p>
         * The <CODE>disconnect</CODE> method frees resources used to maintain a
         * connection to the source.
         * If no resources are in use, <CODE>disconnect</CODE> is ignored.
         * If <CODE>stop</CODE> hasn't already been called,
         * calling <CODE>disconnect</CODE> implies a stop.
        public void disconnect() {
            if(connected) {
                sources[0].close();
            connected = false;
         * Get a string that describes the content-type of the media
         * that the source is providing.
         * <p>
         * It is an error to call <CODE>getContentType</CODE> if the source is
         * not connected.
         * @return The name that describes the media content.
        public String getContentType() {
            if( !connected) {
           throw new java.lang.Error("Source is unconnected.");
            return contentType.getContentType();
        public Object getControl(String str) {
            return null;
        public Object[] getControls() {
            return new Object[0];
        public javax.media.Time getDuration() {
            return Duration.DURATION_UNKNOWN;
         * Get the collection of streams that this source
         * manages. The collection of streams is entirely
         * content dependent. The  MIME type of this
         * <CODE>DataSource</CODE> provides the only indication of
         * what streams can be available on this connection.
         * @return The collection of streams for this source.
        public javax.media.protocol.PullSourceStream[] getStreams() {
            if( !connected) {
           throw new java.lang.Error("Source is unconnected.");
            return sources;
         * Initiate data-transfer. The <CODE>start</CODE> method must be
         * called before data is available.
         *(You must call <CODE>connect</CODE> before calling <CODE>start</CODE>.)
         * @exception IOException Thrown if there are IO problems with the source
         * when <CODE>start</CODE> is called.
        public void start() throws IOException {
         * Stop the data-transfer.
         * If the source has not been connected and started,
         * <CODE>stop</CODE> does nothing.
        public void stop() throws IOException {
    }

  • Unable to understand InputStream.available() method, need some help

    dear friends,
    The following is my doubt. please kindly help me in this. this will help me a lot in understanding some consepts.
    Environment: i am using jdk1.4.1_01 on windowsxp.
    i am using IE6.0 to make requets.
    My requirement:
    what i am actually trying to do is i want to see the raw material
    send by the browser when we made a request to the server
    by the browser.basically i want to see the request line
    and headers as it is that is send by the browser to the server.
    so i thought to code a server that can print the request send
    by the browser as it is on the command window.
    i had taken two examples and i am running Server2.java (look at the bottom for this code)and i made a 25 requests to the server2 program
    which is running on port 8080 by the browser. here only once or twice in 25
    times i was able to see the requests send by the browser.i tried hard and
    found that InputStream.available() method is returning 0 even though the
    request is sucessfully send to the port 8080 that is to the server2 program
    which is listening to port 8080.
    so in this process of experimenting i took Server3.java(i am sending this file
    also as an attachment) which is using multithreading. in this also i did modification
    as i did in Server2.java. the thing is here i am able to succed. here
    InputStream.available method is returning the correct number of bytes
    that are arrived on the port and are available to the InputStream.here
    when ever i made a request from the browser to Server3.java i am able to
    see the raw data send by the browser without failure.
    i could not understand why InputStream.available() is returning 0
    often(not all the time) and why it is giving the desired result when i
    used it in Server3.java ?
    i looked into the documentation and it says " InputStream.available() Returns the number of bytes that can be read (or skipped over) from this input stream without blocking
    by the next caller of a method for this input stream."
    so the thing i could not understand is what is blocking the InputStream
    in the first case.if i could undrstand the internals of how this
    method is working it will help me a lot.if i could understand this i
    will know what is the right situations to use this method.
    Thanking You.
    /*Shows how to develop a simple network server
    Author : Team -J
    Version : 1.0 */
    import java.net.*;
    import java.io.*;
    class Server2{
    static public void main(String[] args)throws Exception{
         // create a new Server Socket
         try{
              ServerSocket ss = new ServerSocket(8080,1);     
         while(true){// set queue length to 1
              // wait for the connections
              Socket s = ss.accept();
              // get the output stream associated with socket
              // to write something to the socket
              PrintStream ps =new PrintStream( s.getOutputStream());
              InputStream is = s.getInputStream();
              ps.println("I am ready to provide xxx Service");
    int len=is.available();
              if(len !=0)
              byte b [] = new byte[len];
              int k =is.read(b,0,(len-1));
              for(int i =0;i<k;i++)
                   char c = (char)b;
                   System.out.print(c);
              // close the connection
              is.close();
              s.close();
         }catch(Exception e){}
    /*Shows how to develop a simple network server
    Author : Team -J
    Version : 1.0 */
    import java.net.*;
    import java.io.*;
    class Server3{
    static public void main(String[] args)throws Exception{
         // create a new Server Socket
         try{
              ServerSocket ss = new ServerSocket(8080,1);
              while(true){
                   // wait for the connections
                   Socket s = ss.accept();
                   ServerThread st = new ServerThread(s);
                   st.start();
         }catch(Exception e){}
    class ServerThread extends Thread{
    Socket s;
         public ServerThread(Socket s){
         this.s = s;
         public void run(){
              try{
              PrintStream ps =new PrintStream( s.getOutputStream());
              InputStream is = s.getInputStream();
              int len=is.available();
              ps.println("I am ready to provide xxx Service");
              if(len!=0)
              byte b [] = new byte[len];
              int k =is.read(b,0,(len-1));
              for(int i =0;i<k;i++)
                   char c = (char)b[i];
                   System.out.print(c);
              is.close();
              s.close();
              }catch(Exception e){}

    so the thing i could not understand is what is
    t is blocking the InputStream
    in the first case.Blocking means the thread goes to sleep waiting for more data to arrive. InputStream.available() shows how many bytes have already arrived, not how many remain to be sent.

  • InputStream / OutputStream Help

    I have in a series 10 commands to be executed on a server. so i am using Buffered OutputStream and DataOutputStream to write those commands to server.
    these commands have a set of protocol rule to be followed.
    for example i am creating a byte array and i am appending those protocol rules to the byte array and then finally to the stream and then writing to the socket of the server.
    everything works fine here.
    After that i must read the messages from the server.
    this is also fine but t�he problem is everytime i read different input for each command.
    i dont know why!!!!
    so my read function is as follows,
    import java.net.*;
    public class xxxxx
    InputStream instream;
    OutputStream outstream;
    public void OpenConnection() throws ConnectException,UnknownHostException
    try
         tcpipSocket = new Socket(tcpipparameters.getIpAddress(),tcpipparameters.getPortNumber());
    catch(IOException exception)
         System.out.println(exception.toString());
    try
         outstream = tcpipSocket.getOutputStream();
         instream = tcpipSocket.getInputStream();
         dos = new DataOutputStream(outstream);
         BufferedOutputStream bos= new BufferedOutputStream(dos);
         dis = new DataInputStream(instream);
         BufferedInputStream bis = new BufferedInputStream(dis);
    ////////// now i start the command execution on the server
    ///// The 1st Command --------------(The INIT Command)
         byte[] init = {0,6,0,2};
         init = createMessage.calculateCheckSum(init);
         int len = init.length;
         //dos.write(init,0,len);
         bos.write(init);
         bos.flush();
         int available;
         while((available = bis.available()) > 0)
              byte[] data = new byte[available];
              bis.read(data);
              for(int i = 0 ; i < data.length; i++)
                   System.out.print(data);
    ////////////////// The 2nd Command -------------------(IDENTIFY)
    byte[] identify = {0,16,0,20};
    // The protocol version number is inserted in to the IDENTIFY byte[]array
    int protocol_version_number = 512;
    byte[] protocol = {(byte)(protocol_version_number/256) ,(byte)(protocol_version_number%256) };
    byte[] temp = new byte[ identify.length +  protocol.length] ;
    System.arraycopy( identify, 0, temp, 0, identify.length ) ;
    System.arraycopy(protocol, 0, temp, identify.length, protocol.length ) ;
    identify = temp ;
    String PR_SName = "PRS2.0";
    identify = createString.stringData(identify,PR_SName);
    identify = createMessage.calculateCheckSum(identify);
    len = identify.length;
    bos.write(identify);
    bos.flush();
    int length1 = bis.available();
    System.out.println("length of the BufferedInputStream = " + length1);
    StringBuffer sb = new StringBuffer();
    for (int i=1; i<=length1; i++)
         char reply = (char)bis.read();
         sb.append(reply);
    System.out.println(sb.toString());
    ////////////////// The 3rd Command and So on................................
    catch(IOException exception)
         System.err.println("message = " + exception.getMessage());
    catch(InterruptedException e)
         System.err.println("Error =" + e);
    finally
         try
              //flush and close both "Instream" and "Outstream"
              dos.close();
              dis.close();
              instream.close();
              outstream.close();
         catch (IOException ex)
              ex.printStackTrace();
    every time the reading from the server is different.
    but i want to have the exact number of bytes to read everytime.
    so please correct me where i am wrong.
    With regards,
    Ashok
              public void CloseConnection()throws IOException
                        tcpipSocket.close();

    I would say the answer is in my previous replies to your question. I suggest you have another read of them.

  • Help with jars webstart and InputStream

    I am currently attempting to fix all the things that break
    the minute you attempt to use a jar under webstart.
    I have attempted to find an answer by searching the forums.
    I cannot determine how to overcome the following.
    I have third party jars for "Jasper reports" and the loadReport
    function requires a java.io.InputStream as input.
    "public static JasperReport loadReport(java.io.InputStream inputStream) throws JRException"
    The report templates are in my jar file in a sub directory "\sreports".
    I was loading the template with the following code.
    JasperReport template = JasperManager.loadReport(new FileInputStream(reportFile));
    Where
    String reportFile = ".\\sreports\\Std"+tableName+".jasper";
    I have tried several things including below.
    FileInputStream fs = new FileInputStream(getClass().getResource("sreports/StdEquipmentType.jasper"));
    which does not even complile.
    Rykk

    Get your input stream like:
    InputStream in = getClass().getResourceAsStream("path/to/file.txt");
    note that you use "/" and not "\" or "\\" no matter what OS you are using.

  • Urgent help: inputstream

    Hi,
    I m defining a BufferedReader and a Inputstream. for example:
         in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                   inStream = socket.getInputStream();
    The BufferedReader is use for reading Strings but i also must read an array of bytes . But when i do inStream.read(bytes) . He gets stuck. Reading like in.readLine() works but then i havent got the array of bytes. So isnt it possible too use both inputstreams ?

    I'd guess trying to read the same stream from two
    different readers at the same time is bad news. Can
    you read the bytes, then make a reader based on the
    byte array?I think i ve found the solution . I send a string for example :
    This is an example. \r\n This is a tes. \r\n byteeeeees
    Now when i use in.readLine(). Then everything what is send so far is encoded using Unicode . So also the bytes of my file. When i m trying to use reading from inputstream then he waits because stream is empty.

  • InputStream........ Help plz....

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import java.net.Socket;
    import javax.swing.ImageIcon;
    class clients extends Object implements java.io.Serializable
         byte[] ml;
    public class CustomerApplet extends JApplet implements java.io.Serializable
         Image img;
         ImageIcon icon;
         public void init()
              Container contentPane=getContentPane();          
              ImageIcon icon;
              try
                   Socket toServer;
                   toServer=new Socket("192.168.1.211",1001);
                   BufferedReader fromServer=new BufferedReader(new InputStreamReader(toServer.getInputStream()));
                   int n;
                   ByteArrayOutputStream a=new ByteArrayOutputStream();
                   InputStream is=null;
                   byte[] b=new byte[200];
                   try
                        while((n = is.read(b)) != -1)
                             a.write(b,0,n);
                   catch (Exception e)
                        System.err.println("Exception : "+e);
                   byte[] xml = a.toByteArray();
                   try
                        icon = new ImageIcon(xml);
                        getAppletContext().showStatus("geting data");
                   catch(Exception e)
                        System.out.println("Failed to create URL:\n" + e);
                        return;
                   fromServer.close();
                   JLabel j1=new JLabel(icon,JLabel.CENTER);
                   contentPane.add(j1);
              catch(InvalidClassException e)
                   getAppletContext().showStatus("the client class is invalid"+e);
              catch(NotSerializableException e)
                   getAppletContext().showStatus("the object is not serializable"+e);
              catch(IOException e)
                   getAppletContext().showStatus("Cannot write to the server"+e);
    }can anyone tell me what must the InputStream in the code above be.........
    Thanks in Advance......
    Uzair........

    i do not understand.......
    may i know what must it be.....
    OutputStream pictStream=
    And the context of that would be what? I see no pictStream in your code, in the first place.
    If someone were to just ask you the same kind of question, would you know what to say?
    I have to conclude that uzair == troll now. A real programmer nor even a wanna-be can't be that brain-dead. Goodbye.

  • How can I convert an InputStream to a FileInputStream ???

    How can I convert an InputStream to a FileInputStream ???

    Thanks for you reply, however, I am still stuck.
    I am trying to convert my application (which runs smoothly) to a signed applet. The following is the original (application) code:
    private void loadConfig() {
    String fileName = "resources/groupconfig";
    File name = new File(fileName);
    if(name.isFile()) {
    try {
         ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
         pAndGConfig = (PAGroupsConfig)in.readObject();
         in.close();
         return;
    } catch(ClassNotFoundException e) {
         System.err.println("++ERROR: "+e);
    } catch(IOException e) {
         System.err.println("++ERROR: "+e);
    System.out.println("Can't find file: " + fileName);
    Because all code and resources now reside in a Jar file (for the signed applet), I must use the following line to access the resources:
    InputStream is = this.getClass().getResourceAsStream(fileName);
    I then need to convert the 'InputStream' to 'ObjectInputStream' or 'FileInputStream' so that I can work with it.
    I would be very grateful if you could help shed some light on the matter - Cobram

  • Error in creating a process using runtime class - please help

    Hi,
    I am experimenting with the following piece of code. I tried to run it in one windows machine and it works fine. But i tried to run it in a different windows machine i get error in creating a process. The error is attached below the code. I don't understand why i couldn't create a process with the 'exec' command in the second machine. Can anyone please help?
    CODE:
    import java.io.*;
    class test{
    public static void main(String[] args){
    try{
    Runtime r = Runtime.getRuntime();
         Process p = null;
         p= r.exec("dir");
         BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
         System.out.println(br.readLine());
    catch(Exception e){e.printStackTrace();}
    ERROR (when run in the dos prompt):
    java.io.IOException: CreateProcess: dir error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:63)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:550)
    at java.lang.Runtime.exec(Runtime.java:416)
    at java.lang.Runtime.exec(Runtime.java:358)
    at java.lang.Runtime.exec(Runtime.java:322)
    at test.main(test.java:16)
    thanks,
    Divya

    As much as I understand from the readings in the forums, Runtime.exec can only run commands that are in files, not native commands.
    Hmm how do I explain that again?
    Here:
    Assuming a command is an executable program
    Under the Windows operating system, many new programmers stumble upon Runtime.exec() when trying to use it for nonexecutable commands like dir and copy. Subsequently, they run into Runtime.exec()'s third pitfall. Listing 4.4 demonstrates exactly that:
    Listing 4.4 BadExecWinDir.java
    import java.util.*;
    import java.io.*;
    public class BadExecWinDir
    public static void main(String args[])
    try
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("dir");
    InputStream stdin = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stdin);
    BufferedReader br = new BufferedReader(isr);
    String line = null;
    System.out.println("<OUTPUT>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
    System.out.println("</OUTPUT>");
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    } catch (Throwable t)
    t.printStackTrace();
    A run of BadExecWinDir produces:
    E:\classes\com\javaworld\jpitfalls\article2>java BadExecWinDir
    java.io.IOException: CreateProcess: dir error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at BadExecWinDir.main(BadExecWinDir.java:12)
    As stated earlier, the error value of 2 means "file not found," which, in this case, means that the executable named dir.exe could not be found. That's because the directory command is part of the Windows command interpreter and not a separate executable. To run the Windows command interpreter, execute either command.com or cmd.exe, depending on the Windows operating system you use. Listing 4.5 runs a copy of the Windows command interpreter and then executes the user-supplied command (e.g., dir).
    Taken from:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

  • I am really sorry but I am still stuck. Please help.

    Please can someone help me with the following code. I have a number of questions. So far all buttons that I have coded actions for work fine. When The program saves it does it correctly as I have seen the text file. However I have some problems.
    1) How can I declare the arrays in another way without setting them to "" when the program starts. I need the program to start and show the previous saved arrays instead. I dont know if my method used for retrieving data from the file is correct either?.
    2) When retrieving the values from a file that has example (all are string values). ADAM SANDLER 111 222 333 MICKY MOUSE 222 444 666
    Where I want them to be in the follwing arrays as an example.
    String name[1] = ADAM
    String surname[1] = SANDLER
    String home[1] = 111
    String work[1] = 222
    String cell[1] = 333
    String name[2] = MICKY
    String surname[2] = MOUSE
    String home[2] = 222
    String work[2] = 444
    String cell[2] = 666
    Here is my code.
         Filename:     ContactsListInterface.java
         Date:           16 March 2008
         Programmer:     Yucca Nel
         Purpose:     Provides a GUI for entering names and contact numbers into a telephone directory.
                        Also allows options for searching for a specific name and deleting of data from the record
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;
    public class ContactsListInterface extends JFrame implements ActionListener
    { //start of class
         // Declare outputstream and inputStream
         DataOutputStream output;
         DataInputStream input;
         String filename = "phonebook";
         // construct fields, buttons, labels and text boxes
         JTextPane displayPane = new JTextPane();
         JLabel listOfContacts = new JLabel("List Of Contacts");               // creates a label for the scrollpane
         JButton createButton = new JButton("Create");
         JButton searchButton = new JButton("Search");
         JButton modifyButton = new JButton("Modify");
         JButton deleteButton = new JButton("Delete");
         // declare data arrays for name, surname, work number, home number and cell number
         private String name[] = {""};
         private String surname[] = {""};
         private String home[] = {""};
         private String work[] = {""};
         private String cell[] = {""};
         // create an instance of the ContactsListInterface
         public ContactsListInterface()
         { // start of cli()
              super("Phonebook Interface");
         } // end of cli()
         public JMenuBar createMenuBar()
         { // start of the createMenuBar()
              // construct and populate a menu bar
              JMenuBar mnuBar = new JMenuBar();                    // creates a menu bar
              setJMenuBar(mnuBar);
              JMenu mnuFile = new JMenu("File",true);               // creates a file menu in the menu bar which is visible
                   mnuFile.setMnemonic(KeyEvent.VK_F);
                   mnuFile.setDisplayedMnemonicIndex(0);
                   mnuFile.setToolTipText("File Options");
                   mnuBar.add(mnuFile);
              JMenuItem mnuFileExit = new JMenuItem("Exit");     // creates an exit option in the file menu
                   mnuFileExit.setMnemonic(KeyEvent.VK_X);
                   mnuFileExit.setDisplayedMnemonicIndex(1);
                   mnuFileExit.setToolTipText("Close Application");
                   mnuFile.add(mnuFileExit);
                   mnuFileExit.setActionCommand("Exit");
                   mnuFileExit.addActionListener(this);
              JMenu mnuEdit = new JMenu("Edit",true);               // creates a menu for editing options
                   mnuEdit.setMnemonic(KeyEvent.VK_E);
                   mnuEdit.setDisplayedMnemonicIndex(0);
                   mnuEdit.setToolTipText("Edit Options");
                   mnuBar.add(mnuEdit);
              JMenu mnuEditSort = new JMenu("Sort",true);          // creates an option for sorting entries
                   mnuEditSort.setMnemonic(KeyEvent.VK_S);
                   mnuEditSort.setDisplayedMnemonicIndex(0);
                   mnuEdit.add(mnuEditSort);
              JMenuItem mnuEditSortByName = new JMenuItem("Sort By Name");          // to sort entries by name
                   mnuEditSortByName.setMnemonic(KeyEvent.VK_N);
                   mnuEditSortByName.setDisplayedMnemonicIndex(8);
                   mnuEditSortByName.setToolTipText("Sort entries by first name");
                   mnuEditSortByName.setActionCommand("Name");
                   mnuEditSortByName.addActionListener(this);
                   mnuEditSort.add(mnuEditSortByName);
              JMenuItem mnuEditSortBySurname = new JMenuItem("Sort By Surname");     // to sort entries by surname
                   mnuEditSortBySurname.setMnemonic(KeyEvent.VK_R);
                   mnuEditSortBySurname.setDisplayedMnemonicIndex(10);
                   mnuEditSortBySurname.setToolTipText("Sort entries by surname");
                   mnuEditSortBySurname.setActionCommand("Surname");
                   mnuEditSortBySurname.addActionListener(this);
                   mnuEditSort.add(mnuEditSortBySurname);
              JMenu mnuHelp = new JMenu("Help",true);                    // creates a menu for help options
                   mnuHelp.setMnemonic(KeyEvent.VK_H);
                   mnuHelp.setDisplayedMnemonicIndex(0);
                   mnuHelp.setToolTipText("Help options");
                   mnuBar.add(mnuHelp);
              JMenuItem mnuHelpHelp = new JMenuItem("Help");          // creates a help option for help topic
                   mnuHelpHelp.setMnemonic(KeyEvent.VK_P);
                   mnuHelpHelp.setDisplayedMnemonicIndex(3);
                   mnuHelpHelp.setToolTipText("Help Topic");
                   mnuHelpHelp.setActionCommand("Help");
                   mnuHelpHelp.addActionListener(this);
                   mnuHelp.add(mnuHelpHelp);
              JMenuItem mnuHelpAbout = new JMenuItem("About");     // creates a about option for info about api
                   mnuHelpAbout.setMnemonic(KeyEvent.VK_T);
                   mnuHelpAbout.setDisplayedMnemonicIndex(4);
                   mnuHelpAbout.setToolTipText("About this program");
                   mnuHelpAbout.setActionCommand("About");
                   mnuHelpAbout.addActionListener(this);
                   mnuHelp.add(mnuHelpAbout);
              return mnuBar;
         } // end of the createMenuBar()
         // create the content pane
         public Container createContentPane()
         { // start of createContentPane()
              // try blocks for the input and output
              try
                   output = new DataOutputStream(new FileOutputStream(filename));
              catch(IOException io)
                   JOptionPane.showMessageDialog(null,"This program could not create a storage location. Please check the disk drive and the tun the program again.","Error",JOptionPane.ERROR_MESSAGE);
                   System.exit(1);
              //construct and populate panels and content pane
              JPanel labelPanel = new JPanel(); // panel is only used to put the label for the textpane in
                   labelPanel.setLayout(new FlowLayout());
                   labelPanel.add(listOfContacts);
              JPanel displayPanel = new JPanel();// panel is used to display all the contacts and thier numbers
                   setTabsAndStyles(displayPane);
                   displayPane = addTextToTextPane();
                   displayPane.setEditable(false);
              JScrollPane scrollPane = new JScrollPane(displayPane);
                   scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // pane is scrollable vertically
                   scrollPane.setWheelScrollingEnabled(true);// pane is scrollable by use of the mouse wheel
                   scrollPane.setPreferredSize(new Dimension(400,320));
              displayPanel.add(scrollPane);
              JPanel workPanel = new JPanel();// panel is used to enter, edit and delete data
                   workPanel.setLayout(new FlowLayout());
                   workPanel.add(createButton);
                        createButton.setToolTipText("Create a new entry");
                        createButton.addActionListener(this);
                   workPanel.add(searchButton);
                        searchButton.setToolTipText("Search for an entry by name number or surname");
                        searchButton.addActionListener(this);
                   workPanel.add(modifyButton);
                        modifyButton.setToolTipText("Modify an existing entry");
                        modifyButton.addActionListener(this);
                   workPanel.add(deleteButton);
                        deleteButton.setToolTipText("Delete an existing entry");
                        deleteButton.addActionListener(this);
              labelPanel.setBackground(Color.red);
              displayPanel.setBackground(Color.red);
              workPanel.setBackground(Color.red);
              // create container and set attributes
              Container c = getContentPane();
                   c.setLayout(new BorderLayout(30,30));
                   c.add(labelPanel,BorderLayout.NORTH);
                   c.add(displayPanel,BorderLayout.CENTER);
                   c.add(workPanel,BorderLayout.SOUTH);
                   c.setBackground(Color.red);
              // add a listener for the window closing and save
              addWindowListener(
                   new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             int answer = JOptionPane.showConfirmDialog(null,"Are you sure you would like to save all changes and exit?","File submission",JOptionPane.YES_NO_OPTION);
                             if(answer == JOptionPane.YES_OPTION)
                                  save();
                                  System.exit(0);
              return c;
         } // end of createContentPane()
         protected void setTabsAndStyles(JTextPane displayPane)
         { // Start of setTabsAndStyles()
              // set Font style
              Style fontStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
              Style regular = displayPane.addStyle("regular", fontStyle);
              StyleConstants.setFontFamily(fontStyle, "SansSerif");
              Style s = displayPane.addStyle("bold", regular);
              StyleConstants.setBold(s,true);
         } // End of setTabsAndStyles()
         public JTextPane addTextToTextPane()
         { // start of addTextToTextPane()
              try
                   input = new DataInputStream(new FileInputStream(filename));
                   for(int i=0; i<name.length;i++)
                        name[i] = input.readUTF();
                        surname[i] = input.readUTF();
                        home[i] = input.readUTF();
                        work[i] = input.readUTF();
                        cell[i] = input.readUTF();
              catch(IOException io)
              Document doc = displayPane.getDocument();
              try
              { // start of tryblock
                   // clear previous text
                   doc.remove(0,doc.getLength());
                   // insert titles of columns
                   doc.insertString(0,"NAME\tSURNAME\tHOME NO\tWORK NO\tCELL NO\n",displayPane.getStyle("bold"));
                   // insert data
                   for(int i=0; i<name.length; i++)
                        doc.insertString(doc.getLength(), name[i] +"\t",displayPane.getStyle("regular"));
                        doc.insertString(doc.getLength(), surname[i] +"\t",displayPane.getStyle("regular"));
                        doc.insertString(doc.getLength(), home[i]+"\t",displayPane.getStyle("regular"));
                        doc.insertString(doc.getLength(), work[i]+"\t",displayPane.getStyle("regular"));
                        doc.insertString(doc.getLength(), cell[i]+"\t",displayPane.getStyle("regular"));
              } // end of try block
              catch(BadLocationException ble)
              { // start of ble exception handler
                   System.err.println("Could not insert text.");
              } // end of ble exception handler
              return displayPane;
         } // end of addTextToTextPane()
         // code to process user clicks
         public void actionPerformed(ActionEvent e)
         { // start of actionPerformed()
              String arg = e.getActionCommand();
              // user clicks exit option
              if(arg.equals("Exit"))
                   int answer = JOptionPane.showConfirmDialog(null,"Exiting will save all changes to file. \nAre you sure you would like to save and exit now?","File submission",JOptionPane.YES_NO_OPTION);
                   if(answer == JOptionPane.YES_OPTION)
                        save();
                        System.exit(1);
              // user clicks help option
              if(arg.equals("Help"))
                   JOptionPane.showMessageDialog(null, "Welcome to the phone book application. To add a new entry press the \"Create\" button.\n To search for an entry press the \"Search\" button.\n To modify an existing entry press the \"Modify\" button. \n To delete an entry press the \"Delete\" button.","Help Topic",JOptionPane.INFORMATION_MESSAGE);
              // user clicks about option
              if(arg.equals("About"))
                   JOptionPane.showMessageDialog(null,"Phonebook v 1.01 created by Yucca Nel.\nNo copyright exists.\nThis program is freeware and should not be sold.\nEnjoy :-)","About phonebook",JOptionPane.INFORMATION_MESSAGE);
              // user clicks create button
              if(arg.equals("Create"))
                   createNew();
              // user clicks search button
              if(arg.equals("Search"))
                   searchForName(arg, name);                    // Only possible to search by name as all contacts Must have a name
              if(arg.equals("Modify"))
                   modifyContact(arg,name);
                   save();
              // user clicks the sort by name option
              if(arg.equals("Name"))
                   sort(name);
              if(arg.equals("Surname"))
                   sort(surname);
         } // end of actionPerformed()
         // Method to ceate a new entry
         public void createNew()
         { // start of createNew()
              int newHome, newWork, newCell = 0;
              String newContactName = JOptionPane.showInputDialog(null,"Please enter the new contacts first name or press cancel to exit.");
              if(newContactName == null)     finish();                         // if user clicks cancel
              if(newContactName.length() <=0)
                   JOptionPane.showMessageDialog(null,"You did not enter a valid name.\nPlease make sure you enter data correctly.","Error",JOptionPane.ERROR_MESSAGE);
                   createNew();                                                  // To return to the create method
              String newContactSurname = JOptionPane.showInputDialog(null,"Please enter the new contacts surname or press cancel to exit.");
              if(newContactSurname == null)     finish();                    // if user clicks cancel
              if(newContactSurname.equals(""))
                   int answer = JOptionPane.showConfirmDialog(null,"You did not enter a surname.\nAre you sure you wish to leave the surname empty?","No data entered",JOptionPane.YES_NO_OPTION);   // Asks if data was valid
                   if(answer == JOptionPane.NO_OPTION)
                        newContactSurname = JOptionPane.showInputDialog(null,"Please enter the new contacts surname.");
              String newContactWorkNum = JOptionPane.showInputDialog(null,"Please enter the new contacts work number or press cancel to exit.");
              if(newContactWorkNum == null)   finish();                    // if user clicks cancel
              String newContactHomeNum = JOptionPane.showInputDialog(null,"Please enter the new contacts home number or press cancel to exit.");
              if(newContactHomeNum == null)     finish();                    // if user clicks cancel
              String newContactCellNum = JOptionPane.showInputDialog(null,"Please enter the new contacts cell number or press cancel to exit.");
              if(newContactCellNum == null)     finish();                    // if user clicks cancel
              // enlarge the arrays so they can accept data
              name = enlargeArray(name);
              surname = enlargeArray(surname);
              work = enlargeArray(work);
              home = enlargeArray(home);
              cell = enlargeArray(cell);
              // add the new data into the arrays
              name[name.length-1] = newContactName;
              surname[surname.length-1] = newContactSurname;
              home[home.length-1] = newContactHomeNum;
              work[work.length-1] = newContactWorkNum;
              cell[cell.length-1] = newContactCellNum;
              // sort the names so they appear in alphebetical order
              sort(name);
         } // end of createNew()
         // The enlarge array method
         //method to enlarge an array by 1
         public String[] enlargeArray(String[] currentArray)
              String[] newArray = new String[currentArray.length + 1];
              for (int i = 0; i < currentArray.length; i++)
              newArray[i] = currentArray;
              return newArray;
         }// End of enlargeArray()
         // The Sort Method
         public void sort(String tempArray[])
         { // start of sort()
              // for loop
              for(int pass = 1; pass < tempArray.length; pass++)
                   for(int element = 0; element < tempArray.length -1; element++)
                   if(tempArray[element].compareTo(tempArray[element+1])>0)
                        swap(name, element, element+1);
                        swap(surname, element, element+1);
                        swap(home, element, element+1);
                        swap(work, element, element+1);
                        swap(cell, element, element+1);
              addTextToTextPane();
         } // end of sort()
         // The swap method
         public void swap(String swapArray[], int first, int second)
         { // start of swap()
              String hold;
              hold = swapArray[first];
              swapArray[first] = swapArray[second];
              swapArray[second] = hold;
         } // end of swap()
         // method to search for a name
         public void searchForName(String searchField, String searchArray[])
         { // start of searchForName()
              try
                   Document doc = displayPane.getDocument();                         // assign text to an object
                   doc.remove(0,doc.getLength());                                        // clear the screen
                   doc.insertString(0,"NAME\tSURNAME\tHOME NO\tWORK NO\tCELL NO\n",displayPane.getStyle("bold"));
                   String searchValue = JOptionPane.showInputDialog(null,"Please enter the 1st name of the person you would like to see phone numbers for or press cancel to exit.");
                   boolean found = false;
                   if(searchValue == null) finish();                                   // if user clicks cancel
                   //search the array
                   for(int i=0; i < name.length; i++)
                        if(searchValue.compareTo(searchArray[i])==0)
                             doc.insertString(doc.getLength(), name[i] +"\t",displayPane.getStyle("regular"));
                             doc.insertString(doc.getLength(), surname[i] +"\t",displayPane.getStyle("regular"));
                             doc.insertString(doc.getLength(), home[i]+"\t",displayPane.getStyle("regular"));
                             doc.insertString(doc.getLength(), work[i]+"\t",displayPane.getStyle("regular"));
                             doc.insertString(doc.getLength(), cell[i]+"\t",displayPane.getStyle("regular"));
                             found = true;
                   if(found == false)
                        JOptionPane.showMessageDialog(null,"No contact with that name found.","No result found",JOptionPane.INFORMATION_MESSAGE);
                        sort(name);
              catch(BadLocationException ble)
                   System.err.println("Could not insert text.");
         } // end of searchForName()
         // Method to modify contact
         public void modifyContact(String searchField, String searchArray[])
         { // start of modifyContact()
              try
                   Document doc = displayPane.getDocument();                         // assign text to an object
                   doc.remove(0,doc.getLength());                                        // clear the screen
                   doc.insertString(0,"NAME\tSURNAME\tHOME NO\tWORK NO\tCELL NO\n",displayPane.getStyle("bold"));
                   String modifyValue = JOptionPane.showInputDialog(null,"Please enter the 1st name of the person you would like to change details for. Or press cancel to exit");
                   boolean found = false;
                   if(modifyValue == null)      finish();                              // if user clicks cancel
                   //search the array
                   for(int i=0; i < name.length; i++)
                        if(modifyValue.compareTo(searchArray[i])==0)
                             // To change the name
                             String oldName = name[i];
                             String newName = JOptionPane.showInputDialog(null,"Please enter a new name if you would like to change the name for "+name[i]+". Or press cancel to exit");
                             if(newName == null)
                                  name[i] = oldName;                                        // if user clicks cancel keep old entry
                                  finish();
                             if(newName.equals(""))                                        // if no data entered then name will stay same
                                  JOptionPane.showMessageDialog(null,"You did not enter a name in the name field.\nOld name will be kept.","Information Message",JOptionPane.INFORMATION_MESSAGE);
                                  name[i] = oldName;
                                  addTextToTextPane();
                             else
                                  name[i] = newName;                                        // new name is saved into array
                                  addTextToTextPane();
                             //To change the surname
                             String oldSurname = surname[i];
                             String newSurname = JOptionPane.showInputDialog(null,"Please enter a new surname if you would like to change the surname for "+name[i]+". Or press cancel to exit");
                             if(newSurname == null)
                                  surname[i] = oldSurname;                              // if user clicks cancel keep old entry
                                  finish();
                             if((oldSurname.length()>0) && newSurname.length()<=0)          // if surname existed but no new surname was entered
                                  int answer = JOptionPane.showConfirmDialog(null,"You are about to remove the surname for "+name[i]+".\nAre you sure you would like to remove the surname for this contact?","Please confirm the following",JOptionPane.YES_NO_OPTION);
                                  if(answer == JOptionPane.YES_OPTION)               // user wishes to remove old surname and leave no surname in place
                                       surname[i] = newSurname;                         // new surname is saved into the array
                                  else                                                       // user does not wish to remove surname
                                       surname[i] = oldSurname;                         // keep the old surname
                             else                                                            // just replace the surname with new one as everything seems fine
                                  surname[i] = newSurname;
                             //To change the work number of contact
                             String oldWork = work[i];
                             String newWork = JOptionPane.showInputDialog(null,"Please enter a new work number if you would like to change the work number for "+name[i]+". Or press cancel to exit");
                             if(newWork == null)
                                  work[i] = oldWork;                                        // user clicks cancel keep old entry
                                  finish();
                             if((oldWork.length()>0) && newWork.length()<=0)          // if number existed but no new number was entered
                                  int answer = JOptionPane.showConfirmDialog(null,"You are about to remove the work number for "+name[i]+".\nAre you sure you would like to remove the work number for this contact?","Please confirm the following",JOptionPane.YES_NO_OPTION);
                                  if(answer == JOptionPane.YES_OPTION)               // user wishes to remove old number and leave no number in place
                                       work[i] = newWork;                                   // new number is saved into the array
                                  else                                                       // user does not wish to remove number
                                       work[i] = oldWork;                                   // keep the old number
                             else                                                            // just replace the number with new one as everything seems fine
                                  work[i] = newWork;
                             //To change the work number of contact
                             String oldHome = home[i];
                             String newHome = JOptionPane.showInputDialog(null,"Please enter a new home number if you would like to change the home number for "+name[i]+". Or press cancel to exit");
                             if(newHome == null)
                                  home[i] = oldHome;                                        // if user clicks cancel keep old value
                                  finish();
                             if((oldHome.length()>0) && newHome.length()<=0)          // if number existed but no new number was entered
                                  int answer = JOptionPane.showConfirmDialog(null,"You are about to remove the home number for "+name[i]+".\nAre you sure you would like to remove the home number for this contact?","Please confirm the following",JOptionPane.YES_NO_OPTION);
                                  if(answer == JOptionPane.YES_OPTION)               // user wishes to remove old number and leave no number in place
                                       home[i] = newHome;                                   // new number is saved into the array
                                  else                                                       // user does not wish to remove number
                                       home[i] = oldHome;                                   // keep the old number
                             else                                                            // just replace the number with new one as everything seems fine
                                  home[i] = newHome;
                             //To change the cell number
                             String oldCell = cell[i];
                             String newCell = JOptionPane.showInputDialog(null,"Please enter a new cell number if you would like to change the cell number for "+name[i]+". Or press cancel to exit");
                             if(newCell == null)
                                  cell[i] = oldCell;                                        // if user clicks cancel keep old value
                                  finish();
                             if((oldCell.length()>0) && newCell.length()<=0)          // if number existed but no new number was entered
                                  int answer = JOptionPane.showConfirmDialog(null,"You are about to remove the Cell number for "+name[i]+".\nAre you sure you would like to remove the cell number for this contact?","Please confirm the following",JOptionPane.YES_NO_OPTION);
                                  if(answer == JOptionPane.YES_OPTION)               // user wishes to remove old number and leave no number in place
                                       cell[i] = newCell;                                   // new number is saved into the array
                                  else                                                       // user does not wish to remove number
                                       cell[i] = oldCell;                                   // keep the old number
                             else                                                            // just replace the number with new one as everything seems fine
                                  cell[i] = newCell;
                             found = true;
                        addTextToTextPane();
                   if(found == false)
                        JOptionPane.showMessageDialog(null,"No contact with that name found.","No result found",JOptionPane.INFORMATION_MESSAGE);
                        sort(name);
                        addTextToTextPane();
              catch(BadLocationException ble)
                   System.err.println("Could not insert text.");
         } // end of searchForName()
         // finish method for cancel button
         public void finish()
              JOptionPane.showMessageDialog(null,"This program will now close and automatically save all data entered. You may restart the program to modify any changes.","Information Message",JOptionPane.INFORMATION_MESSAGE);
              System.exit(0);
         // method to save data to file
         public void save()
              try
                   for(int i=0; i < name.length; i++)
                        output.writeUTF(name[i]);
                        output.writeUTF(surname[i]);
                        output.writeUTF(work[i]);
                        output.writeUTF(home[i]);
                        output.writeUTF(cell[i]);
                   JOptionPane.showMessageDialog(null,"Data succesfully saved to file.","Information message",JOptionPane.INFORMATION_MESSAGE);
              catch(IOException io)
                   System.exit(1);
         public static void main(String[] args)
         { // start of main()
              // Set look and feel of interface
              try
              { // start of try block
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } // end of try block
              catch(Exception e)
              { // start of catch block
                   JOptionPane.showMessageDialog(null,"There was an error in setting the look and feel of this application","Error",JOptionPane.INFORMATION_MESSAGE);
              } // end of catch block
              ContactsListInterface cli = new ContactsListInterface();
              cli.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              cli.setJMenuBar(cli.createMenuBar());
              cli.setContentPane(cli.createContentPane());
              cli.setSize(520,500);
              cli.setVisible(true);
              cli.setResizable(false);
         } // end of main()
    } //end of classBefore thinking I am lazy I dont want you to correct my code. Just give me a few pointers on how to get my arrays back from the file and how to set my strings to  a non null value that wont show when my program starts.
    Edited by: Yucca on Mar 24, 2008 7:24 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              

    Yucca wrote:
    It's pretty easy to write objects to file, but it depends on what you want to do with that file. Do you want it to be a human-readable text file? Is it only to be used by your program? The file is to be used by my program to save to and to read from. But I understand now that saving each entry as a string and not writing it to an array may be easier. Do I use the buffered reader instead of InputStreamReader? Oh sorry I forgot to mention that the file I save to will later be used when I convert my application to a database type/SQL tyype aplication.
    Edited by: Yucca on Mar 24, 2008 8:06 PMIt sounds to me like object serialization would be the easiest for what you want to do. Read through this:
    http://java.sun.com/developer/technicalArticles/Programming/serialization/
    And these apis:
    http://java.sun.com/j2se/1.5.0/docs/api/java/io/ObjectOutputStream.html
    http://java.sun.com/j2se/1.5.0/docs/api/java/io/ObjectInputStream.html

  • Help:Can not find the file in jar!

    Hello everyone:
    I build a project using Netbeans 5.0 and make a jar file with it...
    The code in the project as follows will throw an exception described that it can not find the file named datasource-config.xml
    String dataFilePath = getClass().getResource(dataFile).getPath();
    //System.out.println("filepath:"+dataFilePath);
    InputStream input = new FileInputStream(dataFilePath);
    when I run the project with the main() function as an entry it works perfectly and output:
    filepath:/C:/projects/java_project/search/build/classes/com/cn/wxjt/lucene/config/datasource-config.xml
    But when I compressed the project with jar and run it , it will show:
    filepath:file:/C:/projects/java_project/search/dist/search.jar!/com/cn/wxjt/lucene/config/datasource-config.xml
    there is a (!) between search.jar and /com/cn/wxjt...
    I dont know why I generate a ! symbol in the file path... Is it cause the exception->
    java.io.FileNotFoundException: file:\C:\projects\java_project\search\dist\search.jar!\com\cn\wxjt\lucene\config\datasource-config.xml
    If you have any idea, plz tell me.
    Thank you and best wishes to you !
    :)

    If the file you want to read is in your jar file, use
    getClass ().getResourceAsStream
    (relative_path_file_name)Hope that help,
    Jackhey jack i want to open the file as new File
    i m using this.getClass().getResource("resource/backend.xml");
    the resource is the directory inside the jar file.
    when i prints the url it shows:
    the jar file is in the WORK directory
    URL : jar:file:/home/neeraj/WORK/show.jar!/resource/backend.xml
    now when i creates new File using the url.getFile() method the file does not exist.
    although the same programs runs well when i uses the InputStream
    so plz tell me cant I create a new File from the above method????
    thanks in advance
    with regards
    neeraj

  • Retrieve PCD from Portal...Please Help...Urgent

    Hi Ritu
    i hope you would have fixed your issue by now.
    kindly help me ......
    i am trying to use the below piece of code to fetch the list of iviews from PCD.
    the problem is  i dont understand the error
    Code in APC:
    ===========
    public class APC_Comp extends AbstractPortalComponent
        public void doContent(IPortalComponentRequest request, IPortalComponentResponse response)
           try{
           Hashtable env = new Hashtable();
           env.put(IPcdContext.SECURITY_PRINCIPAL, request.getUser());
           env.put(Context.INITIAL_CONTEXT_FACTORY,IPcdContext.PCD_INITIAL_CONTEXT_FACTORY);
    //       env.put(com.sap.portal.directory.Constants.REQUESTED_ASPECT, PcmConstants.ASPECT_SEMANTICS);
    //           /******** Since i couldnt find      PcmConstants.ASPECT_SEMANTICS jar i used the below code.
           env.put(Constants.REQUESTED_ASPECT,"com.sap.portal.pcd.gl.PersistencyAspect");
           InitialContext ctx = null;
           DirContext dirCtx;
           List roleList = null;
           ctx = new InitialContext(env);
           dirCtx = (DirContext) ctx.lookup("pcd:portal_content/");
           PcdSearchControls pcdSearchControls = new PcdSearchControls();
           pcdSearchControls.setReturningObjFlag(false);
           pcdSearchControls.setSearchScope(
           PcdSearchControls.SUBTREE_WITH_UNIT_ROOTS_SCOPE);
           dirCtx.addToEnvironment(
           Constants.APPLY_ASPECT_TO_CONTEXTS,
           Constants.APPLY_ASPECT_TO_CONTEXTS);
           NamingEnumeration ne = dirCtx.search("","(com.sap.portal.pcd.gl.ObjectClass=com.sapportals.portal.*iview*)",
                                                                       pcdSearchControls);
           while (ne.hasMoreElements()) {
           IPcdSearchResult searchResult =
           (IPcdSearchResult) ne.nextElement();
           String location = "pcd:portal_content/" + searchResult.getName();
           roleList.add(location);
           response.write("Object is "+location);
           }catch(Exception e )
                 response.write("Exception Occured due to :" +e.toString());
    Error Log :
    ==========
    << item 1 : >>#1.5 #001125A585A0005F000003BD0002514800045CAD115E54F3#1227798297334#com.sap.portal.prt.runtime#sap.com/irj#com.sap.portal.prt.runtime#ramesht#150270##n/a##e592fa70bc8511dd9fdd001125a585a0#SAPEngine_Application_Thread[impl:3]_19##0#0#Error##Java###07:04_27/11/08_0078_79979950
    [EXCEPTION]
    {0}#1#java.lang.NoClassDefFoundError: com.sapportals.portal.pcd.gl.PcdSearchControls
    at java.lang.J9VMInternals.verifyImpl(Native Method)
    at java.lang.J9VMInternals.verify(J9VMInternals.java:66)
    at java.lang.J9VMInternals.initialize(J9VMInternals.java:127)

    try something like this :
    if image file:
    ImageIcon image = (new ImageIcon(getClass().getResource("yourpackage/mypackage/image.gif")));
    if text file:
    InputStream is = this.getClass().getResourceAsStream( "yourpackage/mypackage/myfile.xml");
    but all in all , getClass will consume a lot computational power(time). If you have to access so many file, it'd better put it outside the jar

  • Help! Saving an image to stream and recreating it on client over network

    Hi,
    I have an application that uses JDK 1.1.8. I am trying to capture the UI screens of this application over network to a client (another Java app running on a PC). The client uses JDK 1.3.0. As AWT image is not serializable, I got code that converts UI screens to int[] and persist to client socket as objectoutputstream.writeObject and read the data on client side using ObjectInputStream.readObject() api. Then I am converting the int[] to an Image. Then saving the image as JPEG file using JPEG encoder codec of JDK 1.3.0.
    I found the image in black and white even though the UI screens are in color. I have the code below. I am sure JPEG encoder part is not doing that. I am missing something when recreating an image. Could be colormodel or the way I create an image on the client side. I am testing this code on a Win XP box with both server and client running on the same machine. In real scenario, the UI runs on an embedded system with pSOS with pretty limited flash space. I am giving below my code.
    I appreciate any help or pointers.
    Thanks
    Puri
         public static String getImageDataHeader(Image img, String sImageName)
             final String HEADER = "{0} {1}x{2} {3}";
             String params[] = {sImageName,
                                String.valueOf(img.getWidth(null)),
                                String.valueOf(img.getHeight(null)),
                                System.getProperty("os.name")
             return MessageFormat.format(HEADER, params);
         public static int[] convertImageToIntArray(Image img)
             if (img == null)
                 return null;
            int imgResult[] = null;
            try
                int nImgWidth = img.getWidth(null);
                int nImgHeight = img.getHeight(null);
                if (nImgWidth < 0 || nImgHeight < 0)
                    Trace.traceError("Image is not ready");
                    return null;
                Trace.traceInfo("Image size: " + nImgWidth + "x" + nImgHeight);
                imgResult = new int[nImgWidth*nImgHeight];
                PixelGrabber grabber = new PixelGrabber(img, 0, 0, nImgWidth, nImgHeight, imgResult, 0, nImgWidth);
                grabber.grabPixels();
                ColorModel model = grabber.getColorModel();
                if (null != model)
                    Trace.traceInfo("Color model is " + model);
                    int nRMask, nGMask, nBMask, nAMask;
                    nRMask = model.getRed(0xFFFFFFFF);
                    nGMask = model.getRed(0xFFFFFFFF);
                    nBMask = model.getRed(0xFFFFFFFF);
                    nAMask = model.getRed(0xFFFFFFFF);
                    Trace.traceInfo("The Red mask: " + Integer.toHexString(nRMask) + ", Green mask: " +
                                    Integer.toHexString(nGMask) + ", Blue mask: " +
                                    Integer.toHexString(nBMask) + ", Alpha mask: " +
                                    Integer.toHexString(nAMask));
                if ((grabber.getStatus() & ImageObserver.ABORT) != 0)
                    Trace.traceError("Unable to grab pixels from the image");
                    imgResult = null;
            catch(Throwable error)
                error.printStackTrace();
            return imgResult;
         public static Image convertIntArrayToImage(Component comp, int imgData[], int nWidth, int nHeight)
             if (imgData == null || imgData.length <= 0 || nWidth <= 0 || nHeight <= 0)
                 return null;
            //ColorModel cm = new DirectColorModel(32, 0xFF0000, 0xFF00, 0xFF, 0xFF000000);
            ColorModel cm = ColorModel.getRGBdefault();
            MemoryImageSource imgSource = new MemoryImageSource(nWidth, nHeight, cm, imgData, 0, nWidth);
            //MemoryImageSource imgSource = new MemoryImageSource(nWidth, nHeight, imgData, 0, nWidth);
            Image imgDummy = Toolkit.getDefaultToolkit().createImage(imgSource);
            Image imgResult = comp.createImage(nWidth, nHeight);
            Graphics gc = imgResult.getGraphics();
            if (null != gc)
                gc.drawImage(imgDummy, 0, 0, nWidth, nHeight, null);       
                gc.dispose();
                gc = null;       
             return imgResult;
         public static boolean saveImageToStream(OutputStream out, Image img, String sImageName)
             boolean bResult = true;
             try
                 ObjectOutputStream objOut = new ObjectOutputStream(out);
                int imageData[] = convertImageToIntArray(img);
                if (null != imageData)
                    // Now that our image is ready, write it to server
                    String sHeader = getImageDataHeader(img, sImageName);
                    objOut.writeObject(sHeader);
                    objOut.writeObject(imageData);
                    imageData = null;
                 else
                     bResult = false;
                objOut.flush();                
             catch(IOException error)
                 error.printStackTrace();
                 bResult = false;
             return bResult;
         public static Image readImageFromStream(InputStream in, Component comp, StringBuffer sbImageName)
             Image imgResult = null;
             try
                 ObjectInputStream objIn = new ObjectInputStream(in);
                 Object objData;
                 objData = objIn.readObject();
                 String sImageName, sSource;
                 int nWidth, nHeight;
                 if (objData instanceof String)
                     String sData = (String) objData;
                     int nIndex = sData.indexOf(' ');
                     sImageName = sData.substring(0, nIndex);
                     sData = sData.substring(nIndex+1);
                     nIndex = sData.indexOf('x');
                     nWidth = Math.atoi(sData.substring(0, nIndex));
                     sData = sData.substring(nIndex+1);
                     nIndex = sData.indexOf(' ');
                     nHeight = Math.atoi(sData.substring(0, nIndex));
                     sSource = sData.substring(nIndex+1);
                     Trace.traceInfo("Name: " + sImageName + ", Width: " + nWidth + ", Height: " + nHeight + ", Source: " + sSource);
                     objData = objIn.readObject();
                     if (objData instanceof int[])
                         int imgData[] = (int[]) objData;
                         imgResult = convertIntArrayToImage(comp, imgData, nWidth, nHeight);
                         sbImageName.setLength(0);
                         sbImageName.append(sImageName);
            catch(Exception error)
                error.printStackTrace();
             return imgResult;
         }   

    While testing more, I found that the client side is generating color UI screens if I use JDK 1.3 JVM for running the server (i.e the side that generates the img) without changing single line of code. But if I use JDK 1.1.8 JVM for the server, the client side is generating black and white versions (aka gray toned) of UI screens. So I added code to save int array that I got from PixelGrabber to a text file with 8 ints for each line in hex format. Generated these files on server side with JVM 1.1.8 and JVM 1.3. What I found is that the 1.1.8 pixel grabber is setting R,G,B components to same value where as 1.3 version is setting them to different values thus resulting in colored UI screens. I don't know why.

  • Help on ftpClient

    Hi there,
    I am a Oracle Developer and I would request your help in using ftpClient. I am using following code for ftping files and then deleting them from the ftp server.
    import java.io.*;
    import oracle.sql.*;
    import java.io.IOException;
    import sun.net.TransferProtocolClient;
    import sun.net.ftp.FtpClient;
    import java.util.Enumeration;
    import java.util.Vector;
    import FullFtpClient;
    public class ORIX_ftp
    public static int fget
    String host, //FTP server ip address or name
    NUMBER port, //FTP server ftp port number
    String username, //FTP server username
    String password, //FTP server password
    String transtype, //FTP transfer type "ASCII" or "BINARY"
    String remotedir, //Remote or FTP server directory path from where files will be fetched
    String localdir, //Local or Oracle server directory path where files will be fetched
    String filenames, //File names seperated by on Remote or FTP server to be fetched from the
    String deletefile, //Delete file after file transfer from FTP Server to Database Server
    String ErrorMessage[]
    FullFtpClient FullFtpClient = new FullFtpClient();
    int ErrorStatus = 0;
    try
    FullFtpClient = new FullFtpClient(host, port.intValue()); //Making FTP connection
    FullFtpClient.login(username, password); //Logging on to FTP server
    if (transtype == "ASCII")
    FullFtpClient.ascii(); //Setting FTP transfer to ascii mode
    if (transtype == "BINARY")
    FullFtpClient.binary(); //Setting FTP transfer to binary mode
    //ftpClient.cd(remotedir); //Set remote or FTP server directory
    if (null != filenames)
    int StartIndex = 0, PosIndex = 0;
    String fname;
    InputStream is;
    int length;
    byte[] buffer;
    File file_out;
    OutputStream os;
    while (-1 != (PosIndex = filenames.indexOf("///",StartIndex)))
    //For each filename the file will be fetched
    fname = filenames.substring(StartIndex,PosIndex);
    is = FullFtpClient.get(fname);
    length = 1;
    buffer = new byte[1024];
    file_out = new File(localdir + "\\" + fname);
    os = new FileOutputStream (file_out);
    while((length = is.read(buffer)) != -1)
    os.write(buffer, 0, length);
    PosIndex += 3;
    StartIndex = PosIndex;
    if (deletefile != null)
    FullFtpClient.delete (fname); // Remove file from FTP server
    // Last, or only, filename;
    if (StartIndex < filenames.length())
    fname = filenames.substring(StartIndex);
    is = FullFtpClient.get(fname);
    length = 1;
    buffer = new byte[1024];
    file_out= new File(localdir + "\\" + fname);
    os = new FileOutputStream (file_out);
    while((length = is.read(buffer)) != -1)
    os.write(buffer, 0, length);
    if (deletefile != null)
    FullFtpClient.delete (fname); // Remove file from FTP server
    if (FullFtpClient != null)
    // FullFtpClient.delete (filenames);
    FullFtpClient.closeServer(); //Closing the FTP connection
    catch (Exception e)
    ErrorMessage[0] = e.toString();
    ErrorStatus = 1;
    return ErrorStatus;
    Although I am catching the Exception, I get exceptions such as NullPointerException and Dele command could not delete file because access denied.
    What I want is to transfer the file from ftp server and then delete it only after the transfer is complete. Secondly I want to handle any exception whatsoever arises during the execution of this code.
    You help will be of gr8 help.
    Thanx a lot
    Alok

    That is because I don't want to pile the files on the ftp server. Actually the file is transferred from ftp server on to the oracle server, then using javamail its sent to the user and after that there is no point keeping that file on the server. So I want to delete it from both the servers. I am able to delete the file from oracle server but I am unable to delete it from ftp server. Your help would be greatly appreciated.
    Thanks & regards,
    Alok

Maybe you are looking for

  • Update all rows in a View Column via one Apex Form field

    Appreciate any helpful answers to this query. I have an Apex App (4.x) where I have a view: PRICE_MODEL_CRA_V In the view, I have the following applicable columns: COUNTRY GRADE SALARY In the form I have the following fields :P16_COUNTRY (DROPDOWN) :

  • If I can't undo this awful 4.3.3 update how do I fix it??

    I'm so frustrated! I updated my 3G iPhone to the latest update 4.3.3 as usual after I was asked when I plugged it in. What a nightmare! The screen is now too big for my phone and it cuts off pertinent keys (like "reply") in my email app etc.  It's go

  • How do I reduce the number of pixels in a JPG so I can email it?

    I am unable to reduce the number of pixels in a JPG so I can email it == This happened == Every time Firefox opened == 2 days ago

  • How to go back to default setting in a menu for a mac?

    I was wondering if for example I went in system prefrneces and change some options for my mouse. How would I be able to get back to the default setting of my mouse in sysytem prefrences so thing could go back to the way it wa roiginal set. Is this po

  • Debuggin in abap

    hai, can any one help me to know the step by step procedure for debugging in abap from the begining thanking you, vinu karthik