DataOutputStream writeChars() question

I need to write array values that represent a data table to a text file. The array is an Object[]. Here is what I have for each of the data members of the table:
dos.writeChars("CRR");
dos.writeChars(stp1bt1[2].toString());
dos.writeChars("\n");
where dos is the DataOutputStream. It works, sort of. I'm getting a box where the newline character should be when I view the file in wordpad, and there are also boxes in between every character when I view the file in notepad or Word. Is there a different function I should be using instead of writeChars?

the box in wordpad or notepad for the \n is because Windows wants a \r\n combo...
The rest of the boxes are because chars are 2 bytes, so it's writing both bytes, but the high byte is not used for chars that are ASCII (like all English letters and punctuation.
There's nothing wrong with writing chars like that as long as you read it back with a DataInputStream. If you just want to write plain text, you should use Writer and Reader classes.

Similar Messages

  • Text to binary (.txt to .bin)

    Hello,
    I'm developing an application on J2ME that needs to read from files.
    I want to use binary files instead text files, because I think that in this way I have two benefits:
    1. reducing the jar size
    2. speeding up the reading process.
    that's the starting point...and I hope this approach is right.
    I've developed a small class in J2SE just as an utility to convert .txt files in .bin files and...GULP!!!...a txt file of 22KB becomes 44KB converted in .bin...there is something wrong, but I don't know.
    here is the code I wrote:
    package texttobin;
    import java.io.*;
    public class Main {
        public static void main(String[] args) {
            File inFile  = null;    //the file to read
            File outFile = null;    //the file to write
            //read the path from commandline
            if (args.length > 0)
                inFile = new File(args[0]);
                outFile = new File(args[1]);
            //some checkings
            if (inFile == null) return;
            if (outFile == null) return;
            try {
                //setup the streams
                FileOutputStream outputStream = new FileOutputStream (outFile);
                DataOutputStream dataOutputStream = new DataOutputStream (outputStream);
                FileInputStream sourceStream = new FileInputStream(inFile);
                byte readingByte[] = new byte[1];
                while(true) {
                    if (sourceStream.read(readingByte)!=-1) {
                        //to be sure: I convert the readed input byte in a string
                        //and pass the char inside to the writeChar method...
                        dataOutputStream.writeChar(new String(readingByte).charAt(0));
                        //the same result is achieved with:
                        //dataOutputStream.writeChars(new String(readingByte));
                    else break;
                dataOutputStream.close();
                outputStream.close();
                sourceStream.close();
            catch(FileNotFoundException fnfe)
                System.out.println (fnfe);
                return;
            catch(IOException ioe)
                System.out.println (ioe);
                return;
    }WHAT'S WRONG?!
    THANKS A LOT!!!
    daniele

    ZIP it or use a 7-bit encoding scheme (which isn't
    easy). As for faster reading: you need to see that
    the decoding of your file format doesn't take more
    time than the reading of an unencoded format would
    take.Yes, you're right, but I thought that the bottleneck is the reading process, not the decoding algorhytm (hopefully!!!)
    I found an article that say:
    An ASCII file is a binary file that stores ASCII codes. Recall that an ASCII code is a 7-bit code stored in a byte. To be more specific, there are 128 different ASCII codes, which means that only 7 bits are needed to represent an ASCII character.
    However, since the minimum workable size is 1 byte, those 7 bits are the low 7 bits of any byte. The most significant bit is 0. That means, in any ASCII file, you're wasting 1/8 of the bits. In particular, the most significant bit of each byte is not being used.
    http://www.cs.umd.edu/class/spring2003/cmsc311/Notes/BitOp/asciiBin.html
    (and sorry for the mistake: 7-bit not 7 bytes!!!)
    another intrested thing I've found is here:
    http://www2.sys-con.com/ITSG/virtualcd/Java/archives/0607/heaton/index.html
    there is some ways to store strings in bin files (like fstream in C++), but I didn't tested yet if in this way I can reduce the size of the bin.
    The files are stored in the jar file, then zipping maybe can reduce more the size of the jar, but I think that when the stream opens it takes the real bytes of the contained text (well...I'm not sure...may you confirm it?)
    thank you.

  • Sending Chararray of hexadecimal

    Hi everyone.
    im trying to send a chararray of hexadecimal in a socket, but when i catch it on the server it's not the same chararray...
    this is the array i am sending from the client:
      char[] _envio = {0x00,0x4C,0x60,0x00,0x05,0x80,0xE3,0x08,0x00,0x20,0x20,0x61,0x01,0x80,0xC0,0x00,0x02,
                            0x95,0x00,0x00,0x01,0x05,0x82,0x12,0x34,0x01,0x23,0x00,0x01};and this is what i am getting on the server:
    0 4C 60 05 3F E3 8 0 20 20 61 1 3F C0 02 3F 0 0 15 3F12 34 1 23 01
    note that the problem is when the hexadecimal is 0x80, 0x95 and 0x82 it is always change by 3F...
    can someone tell me why this is happening?
    this is how i am sending the chararray
    char[] _envio = {0x00,0x4C,0x60,0x00,0x05,0x80,0xE3,0x08,0x00,0x20,0x20,0x61,0x01,0x80,0xC0,0x00,0x02,
                            0x95,0x00,0x00,0x01,0x05,0x82,0x12,0x34,0x01,0x23,0x00,0x01};
            try
                _serversocket = new Socket(_ipserver, _portserver);
                _out = new PrintStream(_serversocket.getOutputStream());
                _in = new BufferedReader(new InputStreamReader(
                    _serversocket.getInputStream()));
                  _out.println(_envio);
            catch (UnknownHostException ex)
                ex.printStackTrace();
            }and this is how i am chatching it in the server
    try
                    _in = new BufferedReader(new InputStreamReader(
                            _clientsocket.getInputStream()));
                    _out = new PrintStream(_clientsocket.getOutputStream());
                    _in.read(_msj);
                    System.out.print("Mensaje del cliente: ");
                    for(int i = 0; i < _msj.length; i++)
                       System.out.print(Integer.toHexString((int)_msj).toUpperCase());
    System.out.println();
    catch (IOException ex)
    ex.printStackTrace();

    Instead of PrintStream and BufferedReader (with InputStreamReader) you should use [url http://java.sun.com/j2se/1.5.0/docs/api/java/io/DataOutputStream.html#writeChar(int)]DataOutputStream.writeChar() and [url http://java.sun.com/j2se/1.5.0/docs/api/java/io/DataInputStream.html#readChar()]DataInputStream.readChar() because there is no special conversion involved.// client:
    _out = new DataOutputStream(_serversocket.getOutputStream());
    for (int i = 0; i < _envio.length; i++)
        _out.writeChar(_envio);
    // server:
    in = new DataInputStream(clientsocket.getInputStream());
    for (int i = 0; i < _msj.length; i++)
    _msj[i] = _in.readChar();Regards

  • Noobish "efficiency" question on DataOutputStream

    So, I currently have this:
    byte[] buf = some_bytes;
    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    out.writeInt(buf.length);
    out.write(buf);I've always thought that calling write(byte[]) and any given OutputStream will be "efficient", in that things will be chunked under the hood to avoid incurring whatever I/O overhead is present for each and every byte. So, as I understand it, we only need to explicitly use BufferedOutputStream if we're writing one or a few bytes at a time.
    Now I'm not so sure.
    Digging through the core API source code a bit, it seems that this ultimately calls OutputStream.write(byte) in a loop, which, presumably, is bad unless the OutputStream in question is a Buffered one.
    Am I shooting myself in the foot here? Should I be wrapping that DataOuputStream around a BufferedOutputStream? Or vice versa?
    Or should I just scrap the DataOuputStream altogether and write the int's bytes out myself?
    I'm going to test it both ways, but in the meantime, and just in case the tests are not definitive, I'm wondering if anybody here can tell me what I should expect to see.
    I think I've been staring at this stuff for a bit too long and am second-guessing myself to death here no matter which way I look at it. So thanks in advance for any nudge you can give me back toward sanity.
    Edited by: jverd on Feb 16, 2012 3:59 PM

    EJP wrote:
    So, what's the point of the basic OutputStream not being buffered then?I guess the idea was that if you want buffering you say so,Ok.
    I think you'll find that every significant class that extends OutputStream (specifically FileOutputStream and SocketOutputStream) overrides write(byte[], int, int) to do an atomic write to the OS, so it isn't really such an issue except in the case of DataOutputStream (and not ObjectOutputStream, see above).Okay, so, in this case, I've got a DataOutputStream wrapped around a SocketOutputStream. It's not an issue for SOS, but it is for the wrapping DOS. Yes?
    So to overcome the DOS doing a bunch of piddly 1-byte writes to the SOS, which in turn could result in a bunch of piddly 1-byte writes to the network, which I don't want, I inject a BOS between them. Yes?
    Thanks for the help. I can't believe after all these years I never got these details sorted out. I guess it never came up quite this way before.

  • DataOutputStream appears to be buffering and then overflowing?? 10 Duke Pts

    Hi folks,
    Hope someone can help. I am trying to put together a file upload applet (yes I know....security this and signing that and so on...). It "works" (erm...kind of) using the JFileChooser and JProgressMonitorInputStream to carry out an HTTP post to a server side CGI script.
    I have it "working" in so far as with small files it does actually complete although usually some time after the progress bar shows it completed.
    With larger files though the progress bar still rushes through too quickly but then it crashes with an OutOfMemory exception (at around 40MB).
    It looks to me almost as if the DataOutputStream is buffering and returning (not blocking) before the data has actually been sent. I have tried including a .flush() after the write but it made no difference.
    Why does the DataOutputStream return from write before the data has actually been sent?
    If anyone can help in any way it will be massively appreciated! I have included code below its not neat since I have been bashing it around trying to make it work.
    What I am looking for is to have the progress bar show the progress as the contents of the file is uploaded to the server via the HTTP post.
    package videoupload;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    public class VideoUpload extends JApplet implements ActionListener
      class HTTPPoster extends SwingWorker {
        String sBoundary="2db8c22f75474a58cd13fa2d3425017015d392ce";
        URL u;
        public URLConnection postConnect(URL urlTarget)
          URLConnection c = null;
          try {
            c = urlTarget.openConnection();
            // post multipart data
            c.setDoOutput(true);
            c.setDoInput(true);
            c.setUseCaches(false);
          } catch (Exception ex)
             ex.printStackTrace();
          return c;
        public void postHeaders(URLConnection pCon)
          // set some request headers
          pCon.setRequestProperty("Connection", "Keep-Alive");
          pCon.setRequestProperty("HTTP_REFERER", "http://www.<THEWEBSITE>.com/");
          pCon.setRequestProperty("Content-Type",
                                  "multipart/form-data; boundary="+sBoundary);
        public DataOutputStream getFormBodyOutput(URLConnection pCon)
          DataOutputStream dos = null;
          try
            dos = new DataOutputStream(pCon.getOutputStream());
            sendBoundary(dos);
          } catch (Exception ex)
            ex.printStackTrace();
          return dos;
        public void sendBoundary(DataOutputStream dos)
          try
            dos.writeBytes("--"+sBoundary+"\r\n");
          } catch (Exception ex)
            ex.printStackTrace();
        public void postFile(DataOutputStream dos, String name, File f)
          try
            dos.writeBytes(
                "Content-Disposition: form-data; name=\"" + name +
                "\"; filename=\"" + f.getName() +
                "\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            System.out.println("Opening - "+f.getAbsoluteFile());
            FileInputStream fis = new FileInputStream(f.getAbsoluteFile());
            ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(
                content, f.getName(), fis);
            ProgressMonitor pm = pmis.getProgressMonitor();
            pm.setMillisToDecideToPopup(500);
            byte[] bt = new byte[1024];
            int cnt = pmis.read(bt);
            while (cnt == bt.length)
              dos.write(bt, 0, cnt);
              cnt = pmis.read(bt);
            // send the last bit to the server
            dos.write(bt, 0, cnt);
            // now close the file and let the web server know this is the end of this form part
            pmis.close();
            fis.close();
            sendBoundary(dos);
          } catch (Exception ex)
            ex.printStackTrace();
        public void endPost(DataOutputStream dos)
          try
            dos.writeBytes(
                "\r\n--" + sBoundary + "--\r\n\r\n");
            dos.flush();
            dos.close();
          } catch (Exception ex)
            ex.printStackTrace();
        public void getResponse(URLConnection pCon)
          try
            DataInputStream dis =
                new DataInputStream(
                    new BufferedInputStream(pCon.getInputStream()));
            String sIn = dis.readLine();
            while (sIn != null)
              if (sIn != null)
                System.out.println(sIn);
              sIn = dis.readLine();
          } catch (Exception ex)
            ex.printStackTrace();
        public Object construct()
          try
              u = new URL("http://www.<THEWEBSITE>.com/cgi-bin/upload.cgi");
              // System.out's here for debugging only...
              System.out.println("Connect");
              URLConnection pCon = postConnect(u);
              System.out.println("Send headers");
              postHeaders(pCon);
              System.out.println("Begin body");
              DataOutputStream dos = getFormBodyOutput(pCon);
              System.out.println("Send file");
              this.postFile(dos, "file", f);
              System.out.println("End body");
              endPost(dos);
              System.out.println("Get response");
              getResponse(pCon);
              System.out.println("Done");
            catch (Exception ex)
              ex.printStackTrace();
          return null;
      Container content;
      File f;
      protected boolean isStandalone = false;
      protected BorderLayout borderLayout1 = new BorderLayout();
      String uploadPath;
      //Get a parameter value
      public String getParameter(String key, String def)
        return isStandalone ? System.getProperty(key, def) :
            (getParameter(key) != null ? getParameter(key) : def);
      //Construct the applet
      public VideoUpload()
      //Initialize the applet
      public void init()
        try
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        catch (Exception e)
          System.err.println("Error setting native LAF: " + e);
        content = getContentPane();
        content.setBackground(Color.white);
        content.setLayout(new FlowLayout());
        // Come back to this later
        JTextField txtFileName = new JTextField();
        txtFileName.addActionListener(this);
        content.add(txtFileName);
        JButton btnUpload = new JButton("Upload");
        btnUpload.setMnemonic('u');
        btnUpload.addActionListener(this);
        content.add(btnUpload);
        //Create a file chooser
        final JFileChooser fc = new JFileChooser();
        int returnVal = fc.showOpenDialog(content);
        f=fc.getSelectedFile();
        try
          uploadPath = this.getParameter("uploadPath", "/");
        catch (Exception e)
          e.printStackTrace();
      public void actionPerformed(ActionEvent e){
        HTTPPoster worker = new HTTPPoster();
        worker.start();
      //Start the applet
      public void start()
      //Stop the applet
      public void stop()
      //Destroy the applet
      public void destroy()
      //Get Applet information
      public String getAppletInfo()
        return "Applet Information";
      //Get parameter info
      public String[][] getParameterInfo()
        java.lang.String[][] pinfo =
            {"uploadPath", "String", ""},
        return pinfo;
      //Main method
      public static void main(String[] args)
        VideoUpload applet = new VideoUpload();
        applet.isStandalone = true;
        Frame frame;
        frame = new Frame();
        frame.setTitle("Applet Frame");
        frame.add(applet, BorderLayout.CENTER);
        applet.init();
        applet.start();
        frame.setSize(400, 320);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLocation( (d.width - frame.getSize().width) / 2,
                          (d.height - frame.getSize().height) / 2);
        frame.setVisible(true);
    }

    Well after much ploughing through internet I have found much to my dismay that URLConnection is not as great as it may appear as it does buffer all output prior to sending.
    This is fine for everything but file transfers, especially large ones as memory can be an issue.
    Answered own question, doh!

  • I have a question about socket

    I've got a socket question that haven't to work out for two days . If you know something about this question please give me a hand , Thank you .............
    ===================================================
    I want to write a program about PortMapping with Java.
    It means : put one port's data to another port .
    =============================
    Just like :
    There is a Tomcat Web Server listener on the 8080 port, and I want to make a socket that listener on the 9090 port. When the client use the Browse visit my web on 9090 port , this socket will be send this data stream from 9090 port to 8080 port and then the Tomcat Web Server process this data and return the result to client use the 9090 port .
    =============================
    (In order to let this program suit for every model (include c/s and b/s),so I think it must be use the byte[] stream )
    ====================================================
    BinaryPort.java
    package sailing;
    import java.io.*;
    import java.net.*;
    public class BinaryPort implements Runnable
    private ServerSocket listenerSocket;
    private Socket serverSocket;
    private Socket tomcatSocket;
    private Thread myThread;
    private DataInputStream in;
    private DataOutputStream out;
    private ByteArrayOutputStream swapStream;
    public BinaryPort()
    try
    System.out.println("Server is starting ..................");
    this.listenerSocket=new ServerSocket(9090);
    this.tomcatSocket=new Socket("127.0.0.1",8080);
    this.swapStream=new ByteArrayOutputStream();
    this.myThread=new Thread(this);
    this.myThread.start();
    catch(Exception e)
    System.out.println(e);
    public void run()
    while(true)
    try
    this.serverSocket=this.listenerSocket.accept();
    this.in=new DataInputStream(this.serverSocket.getInputStream());
    byte[] buf=new byte[100];
    int rc=0;
    while((rc=in.read(buf,0,buf.length))>0)
    this.swapStream.write(buf,0,rc);
    this.swapStream.flush();
    byte[] resBuf=swapStream.toByteArray();
    this.out=new DataOutputStream(this.tomcatSocket.getOutputStream());
    this.out.write(resBuf,0,resBuf.length);
    this.out.flush();
    //Get The Tomcat Web Server reBack Information
    this.in=new DataInputStream(this.tomcatSocket.getInputStream());
    byte[] buf2=new byte[100];
    int rc2=0;
    this.swapStream=null;
    while((rc2=in.read(buf2,0,buf2.length))>0)
    this.swapStream.write(buf2,0,rc2);
    this.swapStream.flush();
    rc2=0;
    byte[] resBuf2=swapStream.toByteArray();
    this.out=new DataOutputStream(this.serverSocket.getOutputStream());
    this.out.write(resBuf2,0,resBuf2.length);
    this.out.flush();
    this.myThread.sleep(1000);
    this.out.close();
    this.in.close();
    catch(Exception e)
    System.out.println(e);
    public static void main(String args[])
    new BinaryPort();
    ====================================================
    I found that it stop on the first "while" , and I don't know what is the reason .............

    Well , I've got it ~~~~~~~~~
    if the read method hasn't the another data , this method will be stoped . so ..............
    ===============================
    package sailing;
    import java.io.*;
    import java.net.*;
    public class ModifyBinaryPort
         private ServerSocket listenerSocket;
         private Socket serverSocket;
         public ModifyBinaryPort()
              try
                   System.out.println("Server is starting ..................");
                   this.listenerSocket=new ServerSocket(9633);
                   while(true)
                        try
                             this.serverSocket=this.listenerSocket.accept();
                             new MyThread(serverSocket).start();                    
                        catch(Exception e)
                             System.out.println(e);
              catch(Exception e)
                   System.out.println(e);
         public static void main(String args[])
              new ModifyBinaryPort();
         class MyThread extends Thread
              private Socket threadSocket;
              private Socket tomcatSocket;
              private Thread myThread;
              private DataInputStream in;
              private DataOutputStream out;
              public MyThread(Socket socket)
                   try
                        threadSocket=socket;
                        this.tomcatSocket=new Socket("127.0.0.1",9090);
                   catch(Exception e)
                        System.out.println(e);
              public void run()
                   try
                        //Read Thread
                        new ReadClientWriteTomcatThread(threadSocket,tomcatSocket).start();                    
                   catch(Exception e)
                             System.out.println(e);
         class ReadClientWriteTomcatThread extends Thread
              private DataInputStream read;
              private DataOutputStream write;
              private ByteArrayOutputStream swapStream;
              private Socket threadSocket;
              private Socket tomcatSocket;
              public ReadClientWriteTomcatThread(Socket threadSocketT,Socket tomcatSocketT)
                   try
                        threadSocket=threadSocketT;
                        tomcatSocket=tomcatSocketT;
                        read=new DataInputStream(threadSocket.getInputStream());
                        write=new DataOutputStream(tomcatSocket.getOutputStream());
                        this.swapStream=new ByteArrayOutputStream();
                   catch(Exception e)
                        System.out.println(e);
              public void run()
                   try
                        byte[] buf=new byte[100];
                        int rc=0;
                        while((rc=read.read(buf,0,buf.length))>0)
                             this.swapStream.write(buf,0,rc);
                             this.swapStream.flush();
                             if(rc<buf.length)
                                  break;
                             //System.out.println(rc);
                        byte[] resBuf=swapStream.toByteArray();
                        this.write.write(resBuf,0,resBuf.length);
                        this.write.flush();
                        //Reading the result from tomcat
                        new ReadTomcatWriteClientThread(threadSocket,tomcatSocket).start();
                   catch(Exception e)
                        System.out.println(e);
         class ReadTomcatWriteClientThread extends Thread
              private DataInputStream read;
              private DataOutputStream write;
              private ByteArrayOutputStream swapStream;
              public ReadTomcatWriteClientThread(Socket threadSocket,Socket tomcatSocket)
                   try
                        read=new DataInputStream(tomcatSocket.getInputStream());
                        write=new DataOutputStream(threadSocket.getOutputStream());
                        this.swapStream=new ByteArrayOutputStream();
                   catch(Exception e)
                        System.out.println(e);
              public void run()
                   try
                        byte[] buf2=new byte[100];
                        int rc2=0;
                        while((rc2=read.read(buf2,0,buf2.length))>0)
                             this.swapStream.write(buf2,0,rc2);
                             this.swapStream.flush();
                             if(rc2<buf2.length)
                                  break;
                        byte[] resBuf2=swapStream.toByteArray();
                        this.write=new DataOutputStream(write);
                        this.write.write(resBuf2,0,resBuf2.length);
                        this.write.flush();          
                        this.write.close();
                        this.read.close();
                   catch(Exception e)
                        System.out.println(e);
    }==================
    but it still has some little bug , I think I will work out soon .........
    Thanks for your help ejp .............

  • Details for last question I post

    the original code for last question I post(about the DataInputStream& EOFException) is here, thanks if anyone will bother to read it
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.* ;
    public class MasterMindServer
         public MasterMindServer()
              try{
                   ServerSocket serverSocket=new ServerSocket(8000);
                   Socket socket=serverSocket.accept();
                   HandleAClient thread=new HandleAClient(socket);
                   thread.start();
                   }catch(IOException e){System.out.println("Error:"+e.toString());}
         public static void main(String args[])
              new MasterMindServer();
    //inner class
    class HandleAClient extends Thread
         DataOutputStream out;
         DataInputStream in;
         BufferedReader fromFile;
         private Socket socket;
         String line;
         public HandleAClient(Socket socket)
              this.socket=socket;
         public void run()
              int x,o;
              try{
                     out=new DataOutputStream(socket.getOutputStream());
                   in=new DataInputStream(socket.getInputStream());
                   fromFile=new BufferedReader(new FileReader("colorcode.txt"));
                  while((line=fromFile.readLine())!=null)
                    for(int i=0;i<10;i++)
                      String t=in.readUTF();
                      x=check_column(t);
                       System.out.println(x);
                       o=check_color(t);
                       System.out.println(o);
                       out.writeInt(x);
                       out.writeInt(o);
                       if(x==6) break;
                     out.writeUTF(line);
                   socket.close();
                   System.out.println("close");
             }catch(IOException e){
             System.out.println("Error:"+e.toString());}
         public int check_column(String s)
              String str;
              str=s;
              int count=0;
              for(int i=0;i<6;i++)
                   if(s.charAt(i)==line.charAt(i))
                   count++;
              return count;
         public int check_color(String s)
              String str;
              str=s;
              int count=0;
              for(int i=0;i<6;i++)
                   if((line.indexOf(s.charAt(i))!=-1)&&(line.charAt(i)!=s.charAt(i)))
                   count++;
              return count;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.* ;
    public class MasterMindClient extends JFrame implements MouseListener,ActionListener
      /** Default constructor */
      //keep track of the row (or trial) and column number
      int trial_num, col_now ;
      Socket socket;
      int count[]={5,5,5,5,5,5};
    JPanel A[]  = new JPanel[10];
      JPanel B1[] = new JPanel[10];
      JPanel B2[] = new JPanel[10] ;
      JPanel notice = new JPanel() ;
      JPanel sub_notice = new JPanel();
      JPanel D1, D2 ;
      static JTextField [][]color = new JTextField[10][6] ;
      static JTextField [][]Output = new JTextField[10][2];
      static JTextField [][]Answer = new JTextField[1][6] ;
      static JButton []ok = new JButton[10];  
      JLabel L1 = new JLabel("Click the textfield to change color");
      JLabel L2 , L3, L4 ;
      String colorRange="BCGRYW";
      Color colorName[]={Color.black,Color.cyan,Color.green,Color.red,Color.yellow,Color.white};
      String temp ;
    public MasterMindClient() {
        // initialize
        trial_num = 0;
        col_now = 0;
        //sub_notice is Panel where the heading labels are placed
        sub_notice.setLayout(new GridLayout(1,3)) ;
        L2 = new JLabel("  ") ;
        L3 = new JLabel("X");
        L3.setHorizontalAlignment(JTextField.CENTER);
        L4 = new JLabel("O");
        L4.setHorizontalAlignment(JTextField.CENTER);
        L3.setToolTipText("matching color and column");
        L4.setToolTipText("matching color but not matching column" );
        sub_notice.add(L2);
        sub_notice.add(L3);
        sub_notice.add(L4);
        notice.setLayout(new GridLayout(1,2)) ;
        notice.add(L1) ;
        notice.add(sub_notice) ;
        // Get the content pane of the frame
        Container c = getContentPane();
        // Set GridLayout, 4 rows, 3 columns, and gaps 5 between
        // components horizontally and vertically
        c.setLayout(new GridLayout(12, 1, 5, 5));
        c.add(notice);
         JPanel Display = new JPanel() ;
         Display.setLayout(new GridLayout(1,2,5,5)) ;
       //create a Panel for each row to accept use input
       // color[][] textfield is where the user input
       // Output[][] is where to display the number of X and O
        for (int i = 0; i <= A.length-1 ; i++)
        A[i] = new JPanel() ;
        A.setLayout(new GridLayout(1, 2,10,10));
    B1[i] = new JPanel();
    B1[i].setLayout(new GridLayout(1,6,5,5)) ;
    B2[i] = new JPanel();
    B2[i].setLayout(new GridLayout(1,3,5,5)) ;
    for (int j = 0; j <= color[i].length-1 ; j++)
    color[i][j] = new JTextField() ;
    color[i][j].setHorizontalAlignment(JTextField.CENTER);
    if (i == 0)
    {color[i][j].setEditable(true) ;
    else
    {color[i][j].setEditable(false);
    color[i][j].addMouseListener(this);
    B1[i].add(color[i][j]) ;
    } // j loop
    ok[i] = new JButton("SEND");
    if(i==0)
         ok[i].setEnabled(true);
    else
         ok[i].setEnabled(false);
    ok[i].addActionListener(this);
    B2[i].add(ok[i]) ;
    Output[i][0] = new JTextField();
    Output[i][1] = new JTextField();
    Output[i][0].setEditable(false);
    Output[i][1].setEditable(false);
    Output[i][0].setHorizontalAlignment(JTextField.CENTER);
    Output[i][1].setHorizontalAlignment(JTextField.CENTER);
    B2[i].add(Output[i][0]);
    B2[i].add(Output[i][1]);
    A[i].add(B1[i]);
    A[i].add(B2[i]) ;
    c.add(A[i]) ;
    } //for i loop
    //D panel is where we store the answer[][]
    D1 = new JPanel();
    D1.setLayout(new GridLayout(1,6)) ;
    D2 = new JPanel();
    D2.setLayout(new GridLayout(1,2)) ;
    for (int j = 0; j <= Answer[0].length-1 ; j++)
    Answer[0][j] = new JTextField(0) ;
    Answer[0][j].setHorizontalAlignment(JTextField.CENTER);
    Answer[0][j].setEditable(false) ;
    D1.add(Answer[0][j]) ;
    Display.add(D1) ;
    Display.add(D2) ;
    c.add(Display) ;
    public void runClient()
         try
    {      socket=new Socket("localhost",8000);
    DataInputStream in=new DataInputStream(socket.getInputStream());
    int x=0;
    int o=0;
    try{
    while(true)
         while(trial_num<10)
              x=in.readInt();
              //System.out.println(x);
              Output[trial_num][0].setText(String.valueOf(x));
              o=in.readInt();
              //System.out.println(o);
              Output[trial_num][1].setText(String.valueOf(o));
              for(int i=0;i<6;i++)
              color[trial_num][i].setEnabled(false);
         ok[trial_num].setEnabled(false);
         trial_num++;
         col_now=0;
         if(x==6)
                   JOptionPane.showMessageDialog( null, "Congratulation, you've won the game !! " );
                   //ok[trial_num].setEnabled(false);
    break;
         if(trial_num<10)
         {  for(int i=0;i<6;i++)
              color[trial_num][i].setEditable(true);
              count[i]=5;
         ok[trial_num].setEnabled(true);
         if(x!=6)
         {  JOptionPane.showMessageDialog( null, "sorry you did not win the game");
         temp=in.readUTF();
         System.out.println(temp);
         //temp=in.readUTF();
         //System.out.println("can");
         for(int i=0;i<6;i++)
         System.out.println(i);
         char a=temp.charAt(i);
         int index=colorRange.indexOf(String.valueOf(a));
         Answer[0][i].setBackground(colorName[index]);
         trial_num=0;
         for(int j=0;j<10;j++)
         for(int k=0;k<6;k++)
         color[j][k].setBackground(Color.white);
         for(int j=0;j<10;j++)
         for(int k=0;k<2;k++)
         Output[j][k].setText(null);
         for(int i=0;i<6;i++)
              color[trial_num][i].setEditable(true);
              count[i]=5;
         ok[0].setEnabled(true);
         catch(EOFException em){}
         }catch(IOException ex){
              System.out.println("Error:"+ex.toString());}
    public void mouseClicked(MouseEvent e)
    for(int i=0;i<6;i++)
         if(e.getComponent()==color[trial_num][i])
         {         col_now=i;
         break;
    count[col_now]=(count[col_now]+1)%6;
    color[trial_num][col_now].setBackground(colorName[count[col_now]]);
    public void mouseEntered(MouseEvent e)
    public void mouseExited(MouseEvent e)
    public void mouseReleased(MouseEvent e)
    public void mousePressed(MouseEvent e)
    public void actionPerformed(ActionEvent e)
         try{
              send();
         }catch(IOException et){System.out.println("Error:"+et);}
    public void send()throws IOException
         DataOutputStream out=new DataOutputStream(socket.getOutputStream());
         char cbuf[]=new char[6];
         for(int i=0;i<6;i++)
              cbuf[i]=colorRange.charAt(count[i]);
    System.out.println(cbuf);
         out.writeUTF(new String(cbuf));
    /** Main method */
    public static void main(String[] args) {
    MasterMindClient frame = new MasterMindClient();
    frame.setTitle("Master Mind");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocation(300,300) ;
    frame.setSize(450, 450);
    frame.setVisible(true);
    frame.runClient();
    } // end of class

    I notice that you have several hundred lines of GUI code there. None of them have anything to do with the problem you are trying to solve. So put them all aside and write a SMALL test program that does nothing but the little loop you are having a problem with. Shouldn't be more than 20 lines of code.

  • Writing to a URLConnection question

    Hi, I have the following issue hope someone can help!
    Thank you in advcance!
    Eric
    Program Goal
    - Want to write a program that logs in to a website that requires a username and password.
    - The actual URL of the page I want to login:
         http://www.19lou.com/passportlogin.php?action=login
    What I have done
    - I followed the Sun Java Networking Tutorial and wrote the program. Below are the steps:
    1. Create a URL.
    2. Retrieve the URLConnection object.
    3. Set output capability on the URLConnection.
    4. Open a connection to the resource.
    5. Get an output stream from the connection.
    6. Write to the output stream.
    7. Close the output stream.
    Problem
    - I wrote my program and printed the server's response. It says invalid login or password. When I manually
    logon, the username and password work correctly.
    - I suspect that the content line my program HTTP POST to the server is incorrect.
    - Here is segment of my code:
         private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
         private static final String LOGIN_ACTION_NAME = "login";
         private static final String LOGIN_USER_NAME = "test";
         private static final String LOGIN_PASSWORD = "test";
         private static final String TARGET_URL = "http://www.19lou.com/passportlogin.php?action=login";
         //Encode the content to be POSTED
         private String preparePostContent(String loginUserName, String loginPassword) throws UnsupportedEncodingException {
              //Encode username and password to UTF-8 encoding standard
              String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8");
              String encodedLoginPassword = URLEncoder.encode(loginPassword, "UTF-8");
              String content = "login=" + encodedLoginUserName + "&password=" + encodedLoginPassword;
              return content;
         //HTTP POST code
         public HttpURLConnection doHttpPost(String targetUrl, String content) throws IOException {
              HttpURLConnection urlConn = null;
              DataOutputStream dos = null;
              try {
                   //Open a connection to the target URL
                   URL aUrl = new URL(targetUrl);
                   urlConn = (HttpURLConnection)aUrl.openConnection();
                   //Specify that we intend to use this connection for input and output
                   urlConn.setDoInput(true);
                   urlConn.setDoOutput(true);
                   //Specify the content type of our post
                   urlConn.setRequestProperty("Content-Type", POST_CONTENT_TYPE);
                   //Specify the method of HTTP request which is POST
                   //throws ProtocolException
                   urlConn.setRequestMethod("POST");
                   //Prepare an output stream for writing data to the HTTP connection
                   //throws IOException
                   OutputStream os = urlConn.getOutputStream();
                   dos = new DataOutputStream(os);
                   //Writing data
                   //throws IOException
                   dos.writeBytes(content);
                   dos.flush();
                   dos.close();
                   return urlConn;
              catch(IOException e) {
    Questions
    1. Is anything wrong with the content line that's causing the program not being able to login?
         String content = "login=" + encodedLoginUserName + "&password=" + encodedLoginPassword;
    2. Any other parameter that's missing?
    3. The keys here are "login" and "password". Are they the same for every system, even a different language?

    This is a complicated thing. I have used apache's httpclient and ftpclient in the past to circumvent this. The problem is that it then takes you away from URL + URLConnection. Also, I'm not sure you can do SSL with that.
    I recommend you look around the web. I found some good examples of how to do CGI when I was trying to do this.

  • Drag and Drop questions and Serialization in the 1Z0-852 Upgrade exam?

    Hi,
    Does anyone know if the drag and drop items and serialization have been removed from the 1Z0-852 Java SE 6 Programmer Certified Professional UPGRADE exam?
    I know that they have been removed from the 1Z0-851, but not sure about the upgrade exam.
    Thanks in advance,
    Alvaro

    Alvaro wrote:
    Hi,
    Does anyone know if the drag and drop items and serialization have been removed from the 1Z0-852 Java SE 6 Programmer Certified Professional UPGRADE exam?
    I know that they have been removed from the 1Z0-851, but not sure about the upgrade exam.
    Thanks in advance,
    Alvaro(1) Drag and Drop
    .... this question format will have been removed:
    Ref: http://blogs.oracle.com/certification/entry/0596
    (2) Serialization:
    It is best to compare the topics from your notes to the current topics, however according to my reading of the current topics it is in scope at least to some extent:
    http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?page_id=41&p_exam_id=1Z0_852 (Section 3 API Contents):
    Develop code that serializes and/or de-serializes objects using the following APIs from java.io: DataInputStream, DataOutputStream, FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream and Serializable.

  • Another big question!

    Hi,
    I'm sort of new to Java so I'll need some help on this one. I'm not new to programming, though. My question is how do you open a file in java for reading and writing. I want to be able to attach the file input stream to the data input stream so I can read stuff like integers, characters, booleans, strings, ascii characters, etc. How do I do this! Maybe a sample of code will be more clear...
    Input...
    File PollDB = new File("QvtfPoll.db");
    FileInputStream FileIn = new FileInputStream(PollDB);
    DataInputStream Input = new DataInputStream(System.in);
    int YesCount = Input.readInt();
    int NoCount = Input.readInt();
    bool SaidYes = Input.readBoolean();
    FileIn.close();
    Output...
    PollDB.delete();
    PollDB.createNewFile();
    FileOutputStream FileOut = new FileOutputStream(PollDB);
    DataOutputStream Output = new DataOutputStream(System.out);
    YesCount++;
    NoCount++;
    Output.writeInt(YesCount);
    Output.writeInt(NoCount);
    Output.writeBoolean(false);
    Output.flush();
    FileOut.close();
    So you see, that's what I did. But my program freezes. What should I do?

    This is not the right forum for your question. Try the regular "Java Programming" forum.
    However, that code does look reasonable, except for using System.out in the second part. And naming variables with an initial capital letter will drive other Java programmers nuts.
    When you repost this in the other forum, make sure to give details on exactly where it freezes and any other relevant symptoms. (Also check out the [c0de] tag for posting code snippets.)
    -slj-

  • Java Socket Question

    Bonjour all,
    I have a bit of a weird question about Socket output and input streams, when I use the following code everything works fine.
    Socket soc = new Socket("123.456.789.1", 1234);
    +//     Send data request+
    +DataOutputStream dos = new DataOutputStream(soc.getOutputStream());
    dos.writeInt(INT);
    dos.flush();
    +//     Wait for reply+
    ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
    ArrayList<String> files = (ArrayList<String>) ois.readObject();
    How ever if I declare my Output and Input Stream readers together, my program justs hangs.
    Socket soc = new Socket("123.456.789.1", 1234);
    +//     Define streams+
    DataOutputStream dos = new DataOutputStream(soc.getOutputStream());
    ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
    +//     Send data request+
    dos.writeInt(INT);
    dos.flush();
    +//     Wait for reply+
    ArrayList<String> files = (ArrayList<String>) ois.readObject();
    Anyone got any ideas why this is??
    Edited by: 836869 on 15-Feb-2011 04:02

    You have to flush your ObjectOputStream first, it is worth noting that you are not, 1) using an ObjectOutputStream, 2) flushing it before opening the ObjectInputStream.
    Try this.
    ObjectOutputStream oos = new ObjectOutputStream(soc.getOutputStream());
    oos.flush();
    ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());If you want to swap an integer as part of the header, you can do the following.
    ObjectOutputStream oos = new ObjectOutputStream(soc.getOutputStream());
    oos.writeObject(INT);
    oos.flush();
    ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
    Integer intValue = (integer) ois.readObject();

  • Network game communication algorithms... small question

    Just a (hopefully) quick question about getting input from the client side for passing information to a server. At the moment it is set up to take and send the input from the client once the return key is pressed, and send the whole line (with the system.in part). But obviously for a game to be played I am needing the client to send every individual key press from the client. I could try and use the read() method for the bufferedreader, but this returns an int, and I require a string so it can be checked in the server (as I am also going to have a server side representation of the game, as the project is to be investigating lag effects and different solutions to get around online game lag). Or could I use the read() method and use the returned int to find out from that key what was pressed and then change it to the key pressed from the int value returned, or is there a quicker way that doing this check?
    I think there was a method that takes a character array as a parameter and I could somehow set the size to be only 1, so it would send every individual key pressed by the client, then allowing me to send this and display it at the server side? Or am I off on the wrong foot entirely...
    This is the basic code of getting the actual input and then calling the methods which actually sort out writing to the streams elsewhere in the program:
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    s = br.readLine();
    if (s.length() > 0)
    cc.sendMessage(s + "\n");
    Thanks for any help given,
    Cheers

    Hi,
    You could send the KeyEvent object created by the key press event using an ObjectOutputStream or you could just write its code (KeyEvent.getKeyCode()) using DataOutputStream.writeInt().
    If you need the distinction between a press and a release you could write presses as normal key codes and releases as negative key codes.
    In a game I'm making that uses UDP instead of TCP to communicate over the network, since UDP packets aren't guaranteed to get to their destination, whenever a key is pressed or released I send a whole array of integer keyCodes that show which keys are down. This way when a key is released, but the packet indicating the release doesn't get to the server, the server will find out eventually when the next key is pressed/released and a new 'key state' array is sent.

  • Strange DataOutputStream file.

    Thank you in advance for any help you may be able to provide.
    I wasn't sure which forum to post this in, as I'm certainly not new to Java, but not a Pro either- so I put it here so someone with more experience might be able to see it.
    I am trying to create a file using DataOutputStream. I'm using the following code to write the file:
    public static void rewriteFile(String[][] artistAlbum) throws IOException
              System.out.println("Writing file: " + dataB);
              DataOutputStream outputStream = new DataOutputStream(new FileOutputStream(dataB));
              FileOutputStream midman = new FileOutputStream(dataB);
              for(int i=0;i<artistAlbum.length;i++)
                   for(int j=0;j<MAX_SONGS_PER_ALBUM;j++)
                        if(artistAlbum[i][j].equals(END))
                        {j=MAX_SONGS_PER_ALBUM;}
                        else
                             for(int k=0;k<artistAlbum[i][j].length();k++)
                             outputStream.writeChar((int)artistAlbum[i][j].charAt(k)); //<- OutputStream 1
                        outputStream.writeChar('\n'); //<- OutPutStream 2
              outputStream.close();
              System.out.println("");
              System.out.println(dataB + " Written");
         }I've used both writeChar() and writeUTF() for the strings, but neither seems to work properly.
    What I want to get out is:
    Bob Dylan
    1966 Blonde on Blonde
    -Rainy Day Women #12 & 35
    -Pledging My Time
    -Visions of Johanna
    Led Zeppelin
    1969 II
    -Whole Lotta Love
    -What Is and What Should Never Be
    -The Lemon Song
    -Thank You
    Each line in the output is a single piece from artistAlbum[][].
    What I do get is:
    ^@B^@o^@b^@ ^@D^@y^@l^@a^@n^@
    ^@1^@9^@6^@6^@ ^@B^@l^@o^@n^@d^@e^@ ^@o^@n^@ ^@B^@l^@o^@n^@d^@e^@
    ^@-^@R^@a^@i^@n^@y^@ ^@D^@a^@y^@ ^@W^@o^@m^@e^@n^@ ^@#^@1^@2^@ ^@&^@ ^@3^@5^@
    ^@-^@P^@l^@e^@d^@g^@i^@n^@g^@ ^@M^@y^@ ^@T^@i^@m^@e^@
    ^@-^@V^@i^@s^@i^@o^@n^@s^@ ^@o^@f^@ ^@J^@o^@h^@a^@n^@n^@a^@
    ^@
    ^@L^@e^@d^@ ^@Z^@e^@p^@p^@e^@l^@i^@n^@
    ^@1^@9^@6^@9^@ ^@I^@I^@
    ^@-^@W^@h^@o^@l^@e^@ ^@L^@o^@t^@t^@a^@ ^@L^@o^@v^@e^@
    ^@-^@W^@h^@a^@t^@ ^@I^@s^@ ^@a^@n^@d^@ ^@W^@h^@a^@t^@ ^@S^@h^@o^@u^@l^@d^@ ^@N^@e^@v^@e^@r^@ ^@B^@e^@
    ^@-^@T^@h^@e^@ ^@L^@e^@m^@o^@n^@ ^@S^@o^@n^@g^@
    ^@-^@T^@h^@a^@n^@k^@ ^@Y^@o^@u^@
    ^@
    As you can see- not the prettiest sight. writeUTF had a few less, but they were all different. You had ^@ ^% ^$omething else and ^@nother thing. Scattered much more randomly.
    Now just looking at the thing I don't care about, but what my code is trying to do will allow me to read in the data, modify it, then write it back to the same file and be able to read it again. The file has to start off clean, as shown in the first output example.
    My code to read in the data:
    public static String[][] getList() throws IOException
             int[] lineCount = new int[4];
             lineCount = countLines();
             DataInputStream inputStream = new DataInputStream(new FileInputStream(dataB));
              FileInputStream midman = new FileInputStream(dataB);
              int numSections = lineCount[1];
              if (lineCount[2] == 1)
              {numSections--;}
              if (lineCount[3] == 0)
              {numSections++;}
              String[][] artistAlbum = new String[numSections][MAX_SONGS_PER_ALBUM];
              String line = "";
              int section = 0;
              int secLine = 0;
              for(int i=1;i<=lineCount[0];i++)
                   line = inputStream.readLine();
                   if (i == lineCount[3]) //i will never = 0, so lineCount[3] (which can only be 1 or 0)
                   {lineCount[3] = 0;}          //will match only if we need to skip.
                   else if (i == lineCount[0] && lineCount[2] == 0)
                        artistAlbum[section][secLine] = line;
                        secLine++;
                        artistAlbum[section][secLine] = END;
                   else if (line.equals(""))
                        artistAlbum[section][secLine] = END;
                        section++;
                        secLine = 0;
                   else
                        artistAlbum[section][secLine] = line;
                        secLine++;
              inputStream.close();
              return artistAlbum;
        }Which makes a call to:
    public static int[] countLines() throws IOException
             DataInputStream inputStream = new DataInputStream(new FileInputStream(dataB));
              FileInputStream midman = new FileInputStream(dataB);
              int numLines = 0;
              int numBlanks = 0;
              int TFLastBlank = 0; //True or False: Is the last line a blank?
              int TFFirstBlank = 0;//True or False: Is the first line a blank?
              String line = "FirstRun";
              String store = "FirstRun";
              do{
                   store = line;
                   line = inputStream.readLine();
                   if (line != null)
                        numLines++;
                        if (line.equals(""))
                        {numBlanks++;}
                        if (line.equals("") && store.equals("FirstRun"))
                        {TFFirstBlank = 1;}
                   if (line == null && store.equals(""))
                   {TFLastBlank = 1;}
              }while (line != null);
              int[] lineCount = new int[4];
              lineCount[0] = numLines;
              lineCount[1] = numBlanks;
              lineCount[2] = TFLastBlank;
              lineCount[3] = TFFirstBlank;
              inputStream.close();
              return lineCount;
        }This code can read in the newly written code- BUT it doesn't detect all of the blank lines, leaving me with an incorrect input when the file is reread.
    This is the last part of the code I need to get done, but I am unsure as to how to proceed with this part, since no matter how I write the file I get these weird symbols.
    Anyone have any suggestions?
    Edited by: Asylus on Dec 8, 2007 7:32 PM

    It looks to me like you're making this a lot more difficult than it needs to be. Instead of Data[Input/Output]Stream and File[Input/Output]Stream, use a FileWriter wrapped in a BufferedWriter to write the file, and a FileReader wrapped in a BufferedReader to read it.

  • Proxy Questions

    I have two questions regarding HTTP proxy servers:
    1) For redirection codes such as 301, is it more common for the proxy server or the web client to handle the redirection and send another request?
    2) Regarding downloading embedded objects, I would appreciate it if anyone could let me know what would be the quickest or easiest classes and methods to use to read and write binary files. The following block was used for downloading base pages. I plan on making an else statement with similar code (but for downloading and writing binary instead of text)
    /** this code is in a HTTP proxy server
    contentType is a String with the type from the Content-Type header field
    FromOServer is a BufferedReader that reads from the original server
    ToWClient is a DataOutputStream that writes to the web client using the proxy
    if (contentType.equals("text")) {
    response = FromOServer.readLine();
    while (response != null) {
    ToWClient.writeBytes(response + "\r\n");
    response = FromOServer.readLine();
    Please tell me if you have suggestions for which classes and methods would be either easiest or quickest for doing the same thing above except for binary files instead of Strings of text.

    In this reply,
    http://swforum.sun.com/jive/thread.jspa?threadID=97152&tstart=0
    checkout the reply '3'. That explains how to add a regex to block urls.
    but why do you want to deny port 89? (if your requirement is that you want to block a 'local' port -- as opposed to a remote port, -- what you need might be a firewall rather than a proxy.)

  • Multithread questions please take a look.

    if i am going to implement a client application to connect to a server, how many threads do i need?
    i need to have a thread for handling the UI.
    Question : threading for handling the UI for example a textArea if i have 2 textArea that changes its contents do i need 2 thread like 1 thread for textArea1 and another for textArea2?
    i need another thread for staying connected to the serverSocket and sending/recieving data to/from the server.
    Question : where do i call the network thread and the UI thread? both in the main()? or any other methods like calling network thread within UI thread etc?
    thanks alot
    i am new to thread and i have read the tutorial put up by java.sun.com by still unclear about it. please help
    thanks

    What you have to know about threads in Java is that they are as any other objects and you can treat them as such with the difference that the code in the run() method of that object is executed in a different context,so it appears that it is executed simultaniously with any other code in the application. The UI of a java application is executed in a thred which you dont have control over,it is hidden in the framework.In order to achieve flexible design a recommend you to define a class which extends java.lang.Thread and define a variable of the java.net.Socket class there.This class should be instantiated in the main application object.In the run() method implement the logic for reading from the socket,as it will always block if there is no data received. With approach like this you'll avoid UI freezing if you have a Socket object in the main class of the application and it blocks on the read method.
    The logic for data sending you can implement by adding methods in the class you defined which writes to the socket output stream. It is advisable that you implement some kind of notification mechanism from the thred object to the main application object that notifies when data has been received,so you can process it further and show it. Here is some small example:
    class MyApp implements DataReceivalNotificator{//the main class of the application
    private NetClient client;
    public MyApp(String host,int port){
    client = new NetClient(host,port);
    client.addDataReceivedNotificator(this);
    //start the thread;
    client.start();
    public static void main(String[] args){
    MyApp app = new MyApp(args[0],Integer.toString(args));
    app.sendData("Some data for the net:)");
    public synchronized void dataReceived(String data)
    //show the data somehow
    public void sendData(String s){
    client.sendSomeString(s);
    class NetClient extends Thread{
    private Socket soc;
    private DataInputStream inStream;
    private DataOutputStream outStream;
    private String someString;
    private DataReceivalNotificator notifier
    public NetClient(String host,int port){
    try{
    soc = new Socket(host,port);
    inStream = new DataInputStream(new BufferedInputStream(soc.getIputStream()));
    outStream = new DataOutputStream(new BufferedOutputStream(soc.getOutputStream()));
    catch(IOException e){
    public void run(){
    try{
    while(!(someString=outStream.readString()).equals(null)){
    //calls the notifiers method to receive the data
    notifier.dataReceived(someString);
    catch(IOException e){
    public synchronized void sendSomeString(String str){
    try{
    outStream.writeString(str);
    outStream.flush();
    catch(IOException e){
    public void addDataReceivalNotificator(DataReceivalNotificator d){
    notifier = d;
    public interface DataReceivalNotificator
    public void dataReceiver(String data);

Maybe you are looking for

  • BOGO Modifier setup for multiple items

    Regarding the BOGO (buy one, get one free) promo we can set up easily. We have a situation where to set-up a BOGO in which there is one or more "buys" and but only one "get".If there is a case where there are many "gets" though (e.g. Buy "A" and get

  • Login link does not display on website

    When I visit www.history.com the FULL ACCESS video login link does not appear at the top of the home page. History.com support says this is because Shockwave flash is not working correctly. I am using Firefox 35 on a Win7 computer. The Shockwave flas

  • Attachment base64 with apex

    Hi, I'm trying to get some attachments are base64 with apex I always jump when opening decryption errors or open encrypted. My code is: CREATE OR REPLACE /* Formatted on 2012/09/18 10:10 (Formatter Plus v4.8.8) */ FUNCTION SYSTEM.blob_to_blob_base64

  • SAP BI or SAP ECC SAP SD

    Hi All , Looking at long term career prospects ......would it be viable to get into new kind of Technologu with experice of 2.5 years in SAP ECC As I would be working on implementation of BI 7.0 Then would get certified in the same. or should I get c

  • N71 - SAP NetWeaver 7.1 download/installation - Trial

    Dear NetWeaver  installation team, I uninstalled NSP - SAP NetWeaver  7.01 ABAP Trial with the intend to "upgrade" to N71. As I am told in [https://websmp230.sap-ag.de/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/minisap/minisap.htm] : Windows Operating System: