DataOutputStream

Anybody can enlighten me by showing me some sample codes to print out all the vector elements by using DataOutputStream?

hi i dont know much abt dataoutputstream
but u can try either of this two solutions
StringBuffer sb=new StringBuffer();
          while(rs.next())
               sb.append(rs.getString(1));
          FileWriter f=new FileWriter("C:/Data.txt");
          f.write(sb.toString());
          f.close();
          System.out.println("done");
          FileWriter f=new FileWriter("C:/Data.txt");
          while(rs.next())
               f.write(rs.getString(1)+"\n");
          f.close();
          System.out.println("done");

Similar Messages

  • 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!

  • DataInputStream / DataOutputStream  - PS  How do i offer my duke dollars?

    I have written a client server program. The client program establishes a URL connection to a ServerSocket. I am using a DataOutputStream to pass a large amount of data back to the client. The problem is that it appears that every now and then a byte is skipped or lost. Here is the important part of the code. (psudo) This loss appears to happen when I read the bytes into the Buf Array.
    On the ServerSide :
    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
    while (notcomplete){
           dos.writeInt(acuiredInt);
           dos.writeLong(acuiredLong);
            byte[] acuiredBuf ;
            for(int i=0; i < acuiredBuf; i++)
                      dos.writeByte( acuiredBuf) ;
    On the Client Side
    DataInputStream dis = new DataInputStream(new BufferedInputStream(os));
    while (notcomplete){
           dis.readInt(acuiredInt);
           dis.readLong(acuiredLong);
            byte[] acuiredBuf  = new byte[1024];  //always the same size
            for(int i=0; i < acuiredBuf; i++)
                      dis.readByte( ) ;
    }I know that one byte is being lost because I tried to send the same int value acros constantly, and then instead of calling readInt, i called readByte four times (four bytes of an int) , and gradually everytime the mysterios 'loss' happend, the values would shift. See my example:
    1 => 0 , 0 , 0 , 10
    2 => 0 , 0 , 10 , 020
    3 => 0 , 10, 152, 102
    4 => 10 , 82, 152, 102 etc.
    1 <= This displays lets say 500 times and is the correct Representation of the int then...
    2 <= The "020" is not correct, it should be like the line above it. This means that the first 0 has disapeared. (But when i check the last entry in the Buf, the 0 is there) . Afer even some more time it becomes the 3rd line. and the first two zeros are the last two entries in the Buf array.
    So i dont' know if i'm losing information? Using the streams wrong, or how to fix it. All i want to do is pass a large amount of information from the server to the client.
    Any help would be greatly appreciated.

    I know it is not the real code, thats why i said it was psueudo code, because it. For a better explanation of the problem please could you check:
    http://forum.java.sun.com/thread.jspa?threadID=707296&tstart=0

  • DataOutputStream / DataInputStream   ( Losing information? )

    I have written a client server program. The client program establishes a URL connection to a ServerSocket. I am using a DataOutputStream to pass a large amount of data back to the client. The problem is that it appears that every now and then a byte is skipped or lost. Here is the important part of the code. (psudo) This loss appears to happen when I read the bytes into the Buf Array.
    On the ServerSide :
    DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
    while (notcomplete){
           dos.writeInt(acuiredInt);
           dos.writeLong(acuiredLong);
            byte[] acuiredBuf ;
            for(int i=0; i < acuiredBuf; i++)
                      dos.writeByte( acuiredBuf) ;
    On the Client Side
    DataInputStream dis = new DataInputStream(new BufferedInputStream(os));
    while (notcomplete){
           dis.readLong(acuiredLong);
           dis.readInt(acuiredInt);
            byte[] acuiredBuf  = new byte[1024];  //always the same size
            for(int i=0; i < acuiredBuf; i++)
                      dis.readByte( ) ;
    }I know that one byte is being lost because I tried to send the same int value acros constantly, and then instead of calling readInt, i called readByte four times (four bytes of an int) , and gradually everytime the mysterios 'loss' happend, the values would shift. See my example:
    Should Be:  
                  1    =>       0 , 0 , 0 , 10      
                  2    =>       0 , 0 , 10 , 020 
                  3    =>       0 , 10, 152, 102    etc. 1 <= This displays lets say 500 times and is the correct Representation of the int then...
    2 <= The 020 is not correct, it should be like the line above. This means that the first 0 has disapeared. (But when i check the last entry in the Buf, the 0 is there) . Afer even some more time it becomes the 3rd line. and the first two zeros are the last two entries in the Buf array.
    So i dont' know if i'm losing information? Using the streams wrong, or how to fix it. All i want to do is pass a large amount of information from the server to the client.
    Any help would be greatly appreciated.

    In your loop, what aren't you checking the byte array's length rather than comparing against the byte array itself? Does that even compile? Post the actual code that is having issues.
    Also, flushing after writing a single byte is a huge waste. Flush after a 'message' from the client is complete to send to the server and vice versa.
    - Saish

  • CheckedInputStream + DataOutputStream problem

    Hi. I've been working on a simple File transfer / IM program using tcp sockets. I decided to add a checksum calc to the file transfer process, but this led into problems. Here's the problem in detail (code snippet simplified):
    File sender code:
    <code>
    // Tcp connection through Socket fsock
    byte[] buffer = new byte[1024*50];
    DataOutputStream dos = new DataOutputStream(fsock.getOutputStream());
    FileInputStream fis = new FileInputStream("anyfile.wtf");
    CheckedInputStream cin = new CheckedInputStream(fis, new Adler32());
    BufferedInputStream bis = new BufferedInputStream(cin);
    int len = 0;
    while ((len = bis.read(buffer)) != -1)
    dos.write(buffer, 0, len);
    dos.flush();
    //calc checksum etc.
    //close streams
    </code>
    File receiver code:
    <code>
    byte[] buffer = new byte[1024*50];
    DataInputStream dis = new DataInputStream(fsock.getInputStream());
    FileOutputStream fos = new FileOutputStream("anyfile.wtf");
    CheckedOutputStream cout = new CheckedOutputStream(fos, new Adler32());
    BufferedOutputStream bos = new BufferedOutputStream(cout);
    int len = 0;
    while ((len = dis.read(buffer)) != -1)
    bos.write(buffer, 0, len);
    bos.flush();
    // calc checksum etc.
    // close streams
    </code>
    The problem is that, for some reason, in the file receiving end, the dis.read(buffer) call blocks forever (as if it does not receive end of file) and never returns -1.
    If I, however, remove the CheckedInputStream (cin) and connect BufferedInputStream (bis) and FileInputStream (fis) directly, the problem disappears.
    Whats up with this?
    Cheers, Jukka

    Well. I got the program working fine. But I'm still curious as to why I was unable to make the checksum add up to 0, since it would simplify my code a bit further.
    Currently I'm just comparing the checksums calculated at both the sending and receiving end...another stripped code snippet showing this below.
    Sender:
    // open streams
    fdos.writeUTF(file.getName());
    fdos.writeLong(file.length());
    fdos.flush();
    writeMsg("Transferring file (" + file.getName() + ")...");
    int len = 0;
    while ((len = bis.read(buffer)) != -1)
      fdos.write(buffer, 0, len);
    fdos.writeLong(cout.getChecksum().getValue());
    fdos.flush();
    // close streamsReceiver:
    // open streams
    String fname = fdis.readUTF();
    long flength = fdis.readLong();
    writeMsg("Receiving file " + fname + "...");
    long received = 0;
    int len = 0;
    while (received < flength && len != -1)
      if (flength - received < BUFFER_SIZE)
        len = fdis.read(buffer, 0, (int)(flength - received));
        bos.write(buffer, 0, len);
      else
        len = fdis.read(buffer);
        bos.write(buffer, 0, len);
      received += len;
    bos.flush();
    long chksumCalc = cin.getChecksum().getValue(); 
    long chksumRcvd = fdis.readLong();
    // close streamsAny suggestions? Or perhaps a small example that shows how the checksum really evaluates to zero?
    Thanks, Jukka

  • Externalizable vs DataOutputStream/DataInputStream (Storable Interface)

    I have created an interface Storable as below which I use to save a complex Object to a byte array and ultimately to a database. The total processing time is 1hour and 5 minutes.
    public interface Storable
         void readData(DataInputStream in) throws IOException;
         void writeData(DataOutputStream out) throws IOException;
    I then swapped to Externalizable.
    I changed the top Object readData/writeData functions to
    readExternal and writeExternal.
    Then I added new readData/writeData functions to the contained Objects
    as below - so these objects are "new"ed and filled in by my code.
    void readData(InputObject in) throws IOException;
    void writeData(OutputObject out) throws IOException;
    Total processing time was reduced to 33minutes.
    Can anybody explain this >50% speed improvement?
    Also I would rather not use Externalizable so I can decouple the persisted data away from the Java code but it looks like one heck of a time penalty for doing so.

    The point is the only difference between the code I have written is that one is using
    ObjectInput/ObjectOutput (Externalizable) (34 minutes)
    the other is using
    DataOutputStream/DataInputStream (Storable) (1hour 5 minutes)
    and my code for the 2 methods is basically the same.
    This would lead to the conclusion that one of or both Java classes DataOutputStream/DataInputStream are very inefficient and I want to know why?

  • Using DataOutputStream/DataInputStream

    Hi, evveryone.
    I'm needing to use an applet, and this applet uses the following code.
    URL hp = new URL(stringURL);
    URLConnection hpCon = hp.openConnection();
    DataOutputStream dataoutputstream = new DataOutputStream(hpCon.getOutputStream());
    dataoutputstream.writeBytes(DataToSend);
    dataoutputstream.flush();
    dataoutputstream.close();
    DataInputStream datainputstream = new DataInputStream(hpCon.getInputStream());
    Mydoubts are:
    One: the URL used in URLConnection can be an asp page that uses JavaScript, or it must be an pure HTML, or an CGI, etc...
    Two: how, in this URL, can I retrieve the information of DataOutputStream ( I think that is through Request.DataInputStream, but I'm not sure, though ) , and then parse it to a String?
    Third: How I must sent the information that the Applet is waiting ( by an DataInputStreamReader ) back to it? The information is a String.
    Thanks,
    Mivil

    The Usage of URL objects can be facilitated by the following code.
    * Connect to the aURL use the aQueryString
    * as the request parameters and return the
    * data Stream.
    public static InputStream getHTTPResponse(String aURL, String aQueryString) throws MalformedURLException, IOException
    URL url = new URL(aURL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    if (aQueryString != null)
    PrintWriter out = new PrintWriter(connection.getOutputStream());
    out.println(aQueryString);
    out.close();
    return connection.getInputStream();
    * Connect to the aURL use the aQueryString
    * as the request parameters and return the
    * String response (when expected).
    public static String getHTTPResponseString(String aURL, String aQueryString) throws MalformedURLException, IOException
    InputStreamReader ipstr = new InputStreamReader(getHTTPResponse(aURL, aQueryString));
    BufferedReader reader = new BufferedReader(ipstr);
    String inputLine;
    StringBuffer sbuf = new StringBuffer();
    while ((inputLine = reader.readLine()) != null)
    sbuf.append(inputLine);
    reader.close();
    ipstr.close();
    return new String(sbuf);
    Regards

  • NullPointerException during building of a DataOutputStream

    URL url;
    URLConnection urlc;
    try {
    url = new URL("http://", "localhost/", "Post.php");
    urlc = url.openConnection();
    urlc.setDoInput(true);
    urlc.setDoOutput(true);
    urlc.setAllowUserInteraction(false);
    } catch (IOException ioe3) { }
    DataOutputStream tpen = new DataOutputStream(urlc.getOutputStream());
    Well, this is an fragment of my code. During running this aplication, the Java-Console tells me an error. A NullPointerException in the last row of this code fragment. Can anybody tell my, why?

    It is better adding ioe3.printStackTrace() in your catch statement.
    And try url = new URL("http", "localhost", "Post.php");
    Regards,

  • How to send a bigdecimal by DataOutputStream

    Hi Folks!
    Can anybody tell me how i can send a bigDecimal to my client through DataOutputStream object. There are methods in DataOutputStream class for sending long,int,string,double,short and so on BUT there is nothing for bigDecimal.
    Here is my code.
      Socket cs;
      DataInputStream br;
      DataOutputStream dos;
    public void run(){
    try{
         BigDecimal bd = new BigDecimal ( 12342342.234234 ) ;
         bd = bd.setScale ( 1, BigDecimal.ROUND_DOWN ) ;
         System.out.println ( bd ) ;
       //here how i cant send my BigDecimal those dos object?
       dos.
    }catch(Exception e){}
    }Thanks in Advance

    you are correct there is a method bytevalue() in bigDecimal class. which conver my bigDecimal value into bytevalue. WORKS FINE. but on the client side when i receive "BYTEVALUE()" how can i bring it back to the original. Because ofcurse i am gettin my coverted byte value not the original value of bigDecimal..
    Here's how i convert Bigdecimal into bytevalue
         System.out.println("Original "+bd);
         dos.writeByte(bd.byteValue());
         System.out.println("BigInt byte values. "+bd.byteValue());
         dos.flush();now on client side thats how i read it,, BUT bytevalue not the original
        byte b = br.readByte();   
        System.out.println("I got byte value of bigint " + b);   
    Thanks in advance

  • 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.

  • DataOutputStream wrong file format

    I have a small Java Application writing a file, I have been able to get file to be writen as I intended to BUT it comes out UNIX formated....which isn't good for easier text-application such as Ms NotePad.
    How can I tell Java that i want it to use "Windows formating"?
    my code for writing file:
         public void writeToFile(String toWrite) {
              try {
                   FileOutputStream file = new FileOutputStream("XoY.txt", true);
                   BufferedOutputStream buff = new BufferedOutputStream(file,128);
                   DataOutputStream data = new DataOutputStream(buff);
                                data.writeBytes(toWrite);
                   data.close();
                            buff.flush();
              } catch (IOException e) {
                   System.out.println("" + e.getMessage());
              } catch (NullPointerException npe) {
                   System.out.println("" + npe.getMessage());
         }I would be happy about any code you can provide for me.
    Tanx for any help!

    Use \r\n or (better)
    System.getProperty("line.separator") (I think that's
    right) for a newline.thanx for the help even though I dont know where i should insert the code you wrote...
    by the way..here's how i call writeToFile()
                            String toWrite = new String("Nr: " + runs + " X: " + x + " Y: " + y + "\n");
                   writeToFile(toWrite);

  • Difficulties with using DataInputStream and DataOutputStream

    Hello all,
    I need help for understanding what I'm doing wrong here:
    (pass and user are byte[] encrypted with RSA) the problem is that i can;t read what i wrote. :(
    f = new DataOutputStream (new FileOutputStream("file.txt"));
                        f.write(pass);
                        f.write(user);
                        f.flush();
                        f.close();
                        System.out.println ("write pass"+pass);
                        System.out.println ("write user"+user);
                         f2 = new DataInputStream (new FileInputStream("file.txt"));
                        System.out.println("Available bytes"+f2.available());
                        byte [] ru = new byte[64];
                        f2.read(ru,0,64);
                        byte [] rp = new byte[64];
                        f2.read(rp);
                        f2.close();
                        System.out.println( "read user"+ru);
                        System.out.println( "read pass"+rp);//output
    write pass[B@2a4983
    write user[B@406199
    Available bytes128
    read user[B@1b09468
    read pass[B@1df5a8f                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    So you didn't manage to figure it out for yourself - http://forum.java.sun.com/thread.jspa?threadID=5155256&messageID=9587510#9587510 !
    P.S. You need to think more about what you are trying to do and you need to read the Javadoc for DataInputStream and DataOutputStream .
    Message was edited by:
    sabre150

  • Execution halts after DataOutputStream.clos

    I m able to enter the data with the os(DataOutputStream).write to the server but after writing to the server when i m closing the stream the execution halts at os.close . It does not even give an exception but nothing happens after os.close like the System.out.println("well2"); does not print
    try
                            System.out.println("sending : " + _output);
                            System.out.println(_output.getBytes()+"length:"+_output.length());
                            if(flag>0)
                                startApp();//create the http connection here
                            hc.setRequestProperty("Content-Length",Integer.toString(_output.length()));
                            os = hc.openDataOutputStream();
                            System.out.println("back"+_output.getBytes());
                            os.write(_output.getBytes());
                            System.out.println("well2");
                             os.close();
                            flag++;
                            System.out.println("well3");
                        catch(Exception e){System.out.println("connection:"+e);}

    os.close()This ensures the data has been flushed and accepted by the receiver.
    This is probably waiting for the other end to read the data,
    If your sender closes before the data has been read it may be lost or truncated.
    There is a timeout (which you can set on the socket) for this which may be too long for you needs. You can reduce it so that close will throw an exception is a reasonable time frame.

  • 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.

  • Why does DataOutputStream write Boolean as 1 Byte?

    Im trying to conserve space in a file storing booleans.
    why does dataoutputstream write booleans as a byte?
    is there a way to write a bit only?
    thanks!

    Hi,
    A boolean does even allocate at least 8 bits when it is declared in the code.
    From the VM spec:
    "3.2.4 There Is No boolean Type
    Although Java defines a boolean type, the Java Virtual Machine does not
    have instructions dedicated to operations on boolean values. Instead, a
    Java expression that operates on boolean values is compiled to use the int
    data type to represent boolean variables.
    Although the Java Virtual Machine has support for the creation of arrays of
    type boolean (see the description of the newarray instruction), it does not
    have dedicated support for accessing and modifying elements of boolean
    arrays. Arrays of type boolean are accessed and modified using the byte
    array instructions.1
    For more information on the treatment of boolean values in the Java Virtual
    Machine, see Chapter 7, "Compiling for the Java Virtual Machine.""http://java.sun.com/docs/books/vmspec/html/Overview.doc.html#22909
    /Kaj

Maybe you are looking for

  • Device Connected But Not Showing Up In Network Map

    Network Magic Version:  5.5.9195.0 Connection:  Cable Modem:  Linksys WRT54GS2 Firmware:  1.0.02 build 007, Jan 21, 2010 Problem Device:  Blu-ray, wireless Operating System:  Windows 7 Home Premium, Service Pack 1 Anti-virus/Firewall/Spyware:  Micros

  • RE: Dispatcher stopped while restarting of SAP

    Hi, When we are trying to restart SAP server, dispatcher is going to stopped state. For more details i have attched the trace file trc file: "dev_w0", trc level: 1, release: "700" ACTIVE TRACE LEVEL           1 ACTIVE TRACE COMPONENTS      all, MJ B 

  • Can u please tell me events trigaring and first event in report

    hi experts, can u please tell me events trigaring and first event in report

  • 2007 Macbook Black Battery wont recharge?

    I have had to buy 5 new batteries for this macbook.  If the battery is drained of power and not recharged within three days it dies, and can not be recharged.  Does anyone know of any fixes? Better batteries? Apple refunds? Is Apple aware of this hor

  • Is there anyway I can transfer purchases from 1 ID account to a new one?

    Hi, I have an ID account but it has an oldemail address that I can't remember the password to. I want to back up my iPhone on iCloud but I can't verfy it.So I made a new Apple ID account but I dontknow if i can tranfer the purchese I already have on