Java in writting a byte

If we write integer or double through java in a file then the bit pattern for eanch is reverse than any other language (like C/ delphi .e:g delphi writes an integer as A@~! but java writes as !~@A).
How can we convert java pattern to other pattern for integer and float/double?

Then you must split the integers to bytes in the order you want.
You can do it like this
public byte[] toBytes(int i) {
  byte[] b = new byte[4];
  byte b[0] = (i & 0xff000000) >>> 24;
  byte b[1] = (i & 0x00ff0000) >>> 16;
  byte b[2] = (i & 0x0000ff00) >>> 8;
  byte b[3] = i & 0x000000ff;
public int toInt(byte[] b) {
  int i = (b[0]<<24)+(b[1]<<16)+(b[2]<<8)+b[3];
}Maybe this example is in the reverse order that you want, but it's easy to make it the other way around.
With these methods you can read and write bytes from a stream and convert them to and from integers.
Regarding float, you can convert it to an int first, and then use
float f = Float.intBitsToFloat(toInt(b));
where b again is a bytearray of 4 bytes using the described method.
Something similar can be done with long and double.

Similar Messages

  • Most efficient way to write 4 bytes at the start of any file.

    Quick question: I want to write 4 bytes at the start of a file without overriding the current bytes in the file. E.g. push bytes 0-4 along... Is my only option writing the bytes into a new file then writing the rest of the file after? RAF is so close but overrides :(.
    Thanks Mel

    I revised the code to use a max of 8MB buffers for both the nio and stdio copies...
    Looks like NIO is a pretty clear winner... but your milage may vary, lots... you'd need to test this 100's of times, and normalize, to get any "real" metrics... and I for one couldn't be bothered... it's one of those things that's "fast enough"... 7 seconds to copy a 250 MB file to/from the same physical disk is pretty-effin-awesome really, isn't it? ... looks like Vista must be one of those O/S's (mentioned in the API doco) which can channel from a-to-b without going through the VM.
    ... and BTW, it took the program which produced this file 11,416 millis to write it (from an int-array (i.e. all in memory)).
    revised code
    package forums;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.nio.channels.FileChannel;
    class NioBenchmark1
      private static final double NANOS = Math.pow(10,9);
      private static final int BUFF_SIZE = 8 * 1024 * 1024; // 8
      interface Copier {
        public void copy(File source, File dest) throws IOException;
      static class NioCopier implements Copier {
        public void copy(File source, File dest) throws IOException {
          FileChannel in = null;
          FileChannel out = null;
          try {
            in = (new FileInputStream(source)).getChannel();
            out = (new FileOutputStream(dest)).getChannel();
            final int buff_size = Math.min((int)source.length(),BUFF_SIZE);
            long n = -1;
            int pos = 0;
            while ( (n=in.transferTo(pos, buff_size, out)) == buff_size ) {
              pos += n;
          } finally {
            if(in != null) in.close();
            if(out != null) out.close();
      static class NioCopier2 implements Copier {
        public void copy(File source, File dest) throws IOException {
          if ( !dest.exists() ) {
            dest.createNewFile();
          FileChannel in = null;
          FileChannel out = null;
          try {
            in = new FileInputStream(source).getChannel();
            out = new FileOutputStream(dest).getChannel();
            final int buff_size = Math.min((int)in.size(),BUFF_SIZE);
            long n = -1;
            int pos = 0;
            while ( (n=out.transferFrom(in, 0, buff_size)) == buff_size ) {
              pos += n;
          } finally {
            if(in != null) in.close();
            if(out != null) out.close();
      static class IoCopier implements Copier {
        private byte[] buffer = new byte[BUFF_SIZE];
        public void copy(File source, File dest) throws IOException {
          InputStream in = null;
          FileOutputStream out = null;
          try {
            in = new FileInputStream(source);
            out = new FileOutputStream(dest);
            int count = -1;
            while ( (count=in.read(buffer)) != -1) {
              out.write(buffer, 0, count);
          } finally {
            if(in != null) in.close();
            if(out != null) out.close();
      public static void main(String[] arg) {
        final String filename = "SieveOfEratosthenesTest.txt";
        //final String filename = "PrimeTester_SieveOfPrometheuzz.txt";
        final File src = new File(filename);
        System.out.println("copying "+filename+" "+src.length()+" bytes");
        final File dest = new File(filename+".bak");
        try {
          time(new IoCopier(), src, dest);
          time(new NioCopier(), src, dest);
          time(new NioCopier2(), src, dest);
        } catch (Exception e) {
          e.printStackTrace();
      private static void time(Copier copier, File src, File dest) throws IOException {
        System.gc();
        try{Thread.sleep(1);}catch(InterruptedException e){}
        dest.delete();
        long start = System.nanoTime();
        copier.copy(src, dest);
        long stop = System.nanoTime();
        System.out.println(copier.getClass().getName()+" took "+((stop-start)/NANOS)+" seconds");
    output
    C:\Java\home\src\forums>"C:\Program Files\Java\jdk1.6.0_12\bin\java.exe" -Xms512m -Xmx1536m -enableassertions -cp C:\Java\home\classes forums.NioBenchmark1
    copying SieveOfEratosthenesTest.txt 259678795 bytes
    forums.NioBenchmark1$IoCopier took 14.333866455 seconds
    forums.NioBenchmark1$NioCopier took 7.712665715 seconds
    forums.NioBenchmark1$NioCopier2 took 6.206867074 seconds
    Press any key to continue . . .Having said that... The NIO has lost a fair bit of it's charm... testing transferTo's return value and maintaining your own position in the file is "cumbsome" (IMHO)... I'm not even certain that mine is completely correct (?n+=pos or n+=pos+1?).... hmmm..
    Cheers. Keiths.

  • Java.io.UTFDataFormatException: Invalid byte 1 of 1-byte UTF-8 sequence.

    Hi,
    I see the below error when I try to import bunch of email templates.
    com.waveset.util.WavesetException: ==> java.io.UTFDataFormatException: Invalid byte 1 of 1-byte UTF-8 sequence.
    Can any one explain me why is this happenining?
    Thanks,
    Siddiqui

    Hi Siddiqui,
    It looks like u r importing some characters those are not valid UTF-8 character set and some time this type of error comes when u try to import characters like *<,>* so use *& lt;* for < and *>* for >.
    sorry those Characters r not display properly :-(
    Thanx
    Shant
    Edited by: Shant on Jan 18, 2008 6:19 AM
    Edited by: Shant on Jan 18, 2008 6:23 AM

  • How to program in JAVA to write a file to CD

    Hi,
    How to write a program in JAVA to write a file in CD (Using CD-Writer)...

    Install packet-writing software and then write to the cd just like any drive.
    If you're using Windows XP, it has basic capabilities for this built in.
    http://support.microsoft.com/default.aspx?kbid=306524
    http://support.microsoft.com/default.aspx?kbid=279157

  • Can two java program write to the same port by fetching data from different

    can two java program write to the same port by fetching data from different ports, if yes is thing possible for a 3rd program to get all data (is there any data loss or collision)
    how is this possible

    can two java program write to the same port by fetching data from different portsTwo java clients can connect to the same server port and they can both write to it. However the server will see the connections as two separate accepted sockets.

  • How to  write the bytes out

    I have the working code to write the byte[] to the OutputStream, and it works
           ServletOutputStream out = null;
           BufferedInputStream in = null;
            try {
                byte[] bytes = new byte[1024];
                raf = new RandomAccessFile(restoreZipFile, "r");
                raf.seek(10);
                raf.readFully(bytes);
                out = resp.getOutputStream();
                 in = new BufferedInputStream(new ByteArrayInputStream(bytes));
                 int data;
                 while ((data = in.read()) != -1) {
                     out.write(data);
                 out.write(bytes);
                 out.close();
                 in.close();
             catch (Exception e) {
                 log.error("Failed to write.", e);
             }Then, I thought about it. I think it was silly to use the BufferedInputStream again snice the RandomAccessFile already reads to byte[]. Therefore, I skipped the BufferedInputStream and it works. Please correct me if I skipped the BufferedInputStream is a bad idea, thank!
           ServletOutputStream out = null;
            try {
                byte[] bytes = new byte[1024];
                raf = new RandomAccessFile(restoreZipFile, "r");
                raf.seek(10);
                raf.readFully(bytes);
                out = resp.getOutputStream();
                out.write(bytes);
                out.close();
             catch (Exception e) {
                 log.error("Failed to write.", e);
                 return false;
             }

    Your first code sample writes the data out twice, right?
    //once:
    in = new BufferedInputStream(new ByteArrayInputStream(bytes));
    int data;
    while ((data = in.read()) != -1) {
        out.write(data);
    //twice:
    out.write(bytes);And yes, the second way is simpler.

  • JCo writeHTML (java.io.Writer writer)

    Hello,
    I am using writeHTML(java.io.Writer writer) to dump something to a JSP page.
    However this call seems to close the "out" descriptor, which I think is programming with side effects and as such not correct. Has anyone experienced the same problem?
    kind regards,
    Frans.

    Hi Frans,
    I believe the writeHTML method is only intended for debugging purposes.
    However, you could use a StringWriter to buffer the results like this:
    StringWriter sw = new StringWriter();
    jco.writeHTML(sw);
    out.println(sw.toString());
    Hope this helps.
    Best regards,
    Daniel

  • Oracle BLOB Writes the Bytes Twice to Output Stream

    Hi,
    I have a very strange problem when working with oracle.sql.BLOB; I cannot figure out what it's causing my BLOB stream output to double the amount of data inserted into the Oracle database. I have a table that contains two BLOB objects(image files) and the goal is to insert two images into each row by BLOB stream.
    For example, if the image_bin size is 800k and image_thumbnail size is 100k, this code actually writes 1600k (double) and 200k (double) the amount of bytes to each BLOB column, respectively. The print method in insertBlob() indicates a correct number of bytes being written to the output stream (800k and 100k).
    I know for the fact the retrieval method (not mentioned here) doesn't duplicate the bytes when it's read because I have written another test program that does not utilize oracle.sql.BLOB but instead uses PreparedStatement's setBinaryStream(index, InputStream, size_of_file) and it accurately writes the exact image size (no double sizing) to the database -- but not with BLOB. Here's a snippet of my code, note that the actual writing occurs in insertBlob():
    private void insertBlob(java.sql.Blob lobImage, String imgName)
    throws SQLException, IOException {
    File imgFile = null;
    FileInputStream imgOnDisk = null;
    OutputStream imgToDB = null;
    int bufferSize = 0;
    oracle.sql.BLOB blobImage = (oracle.sql.BLOB) lobImage;
    try {
    int bytesRead = 0;
    long bytesWritten = 0L;
    byte[] byteBuffer = null;
    bufferSize = blobImage.getBufferSize();
    byteBuffer = new byte[bufferSize];
    imgFile = new File(imgName);
    // Stream to read the file from the local disk
    imgOnDisk = new FileInputStream(imgFile);
    // Stream to write to the Oracle database
    imgToDB = blobImage.setBinaryStream(imgFile.length());
    // Read from the disk file and write to the database
    while ((bytesRead = imgOnDisk.read(byteBuffer)) != -1 ) {
    imgToDB.write(byteBuffer, 0, bytesRead);
    bytesWritten += bytesRead;
    } // end of while
    System.out.print("Done. " + bytesWritten + "-bytes inserted, buffer size: " +
    bufferSize + "-bytes, chunk size: " +
    blobImage.getChunkSize() + ".\n");
    } catch (SQLException sqlEx) {
    System.out.println("SQLException caught: JDBCOracleLOBBinaryStream.processBlob()");
    connRollback();
    throw sqlEx;
    } catch (IOException ioe) {
    System.out.println("IOException caught: JDBCOracleLOBBinaryStream.processBlob()");
    throw ioe;
    } finally {
    try {
    if (imgOnDisk != null ) {
    imgOnDisk.close();
    if (imgToDB != null ) {
    imgToDB.close();
    } catch (IOException ioeClosing) {
    System.out.println("IOException caught: JDBCOracleLOBBinaryStream.processBlob() " +
    "on closing stream.");
    ioeClosing.printStackTrace();
    } // end of finally
    public void insertImageIntoOracleDB() throws SQLException, IOException {
    PreparedStatement pstmt = null;
    Statement stmt = null;
    ResultSet rset = null;
    try {
    this.getConnection(_driver, host, port, database, user, _pass);
    pstmt = conn.prepareStatement("INSERT INTO " +
    " gallery_v (picture_id, picture_title, image_bin, image_thumbnail) " +
    " VALUES (?, ?, EMPTY_BLOB(), EMPTY_BLOB())");
    pstmt.setInt(1, picID);
    pstmt.setString(2, picTitle);
    pstmt.executeUpdate();
    stmt = conn.createStatement();
    rset = stmt.executeQuery("SELECT image_bin, image_thumbnail FROM gallery_v " +
    " WHERE picture_id = " + picID + " FOR UPDATE");
    int rsetCount = 0;
    oracle.sql.BLOB imgBlob = null;
    oracle.sql.BLOB imgThumbBlob = null;
    while (rset.next()) {
    imgBlob = ((OracleResultSet) rset).getBLOB("image_bin");
    System.out.print("Inserting " + img + "... ");
    insertBlob(imgBlob, img);
    imgThumbBlob = ((OracleResultSet) rset).getBLOB("image_thumbnail");
    System.out.print("Inserting " + imgThumb + "... ");
    insertBlob(imgThumbBlob, imgThumb);
    rsetCount++;
    System.out.println("\nNumber of rows updated: " + rsetCount);
    conn.commit();
    } catch (SQLException sqlEx) {
    System.out.println("SQLException caught: JDBCOracleLOBBinaryStream.insertImageIntoOracleDB()");
    connRollback();
    throw sqlEx;
    } catch (IOException ioe) {
    throw ioe;
    } finally {
    try {
    if (rset != null) {
    rset.close();
    if (pstmt != null) {
    pstmt.close();
    if (stmt != null) {
    stmt.close();
    closeConnection();
    } catch (SQLException closingSqlEx) {
    System.out.println("SQLException caught: JDBCOracleLOBBinaryStream.insertImageIntoOracleDB() " +
    "on closing ResultSet or PreparedStatement.");
    closingSqlEx.printStackTrace();
    } // end of finally
    }

    Make a lumpy mistake; the new BLOB#setBinaryStream() method takes a position of where the data is read from in the stream given to it. So the following code:
    imgToDB = blobImage.setBinaryStream(imgFile.length());
    Starts off from the end of the file. Now I don't understand how this position would result in the duplicated amount of bytes read from the binary file (an image here) to the output stream! The correct line should be:
    imgToDB = blobImage.setBinaryStream(0L);
    ARGH!!! Now everything works as it expected. I gotta read the API's more carefully as I was expecting the same semantic parameter as PreparedStatement#setBinaryStream() which takes the length of the stream as one of its parameters.

  • Writting to Bytes

    Hi all Java Minds......
    In my project, am in need to write bytes as follows. For eg,. if we take Credit card, the card number should have card id with 16 bytes.
    The card id was splitted as
    Card Type - 2 Bytes
    Version - 2 Bytes
    Unique ID - 4 Bytes
    Card Flag - 1 Byte
    Card Specific Type - 2 Bytes
    Reserved for others - 5 Bytes.
    So I need to create 16 Bytes Card ID with this specification. How can this should be? I'm new to this. Please help me. If any one know, please let me know the way and sample source.
    Thanks & Regards,
    Sakthivel Thangasamy
    [email protected]

    Hi Friend
    You can make a data Structure for your cardID
    I am giving you two examples
    check if anyone can help you otherwise gaive a bried what kind of values you are expecting to put init
    class cardID implements Serializable
              byte cardtype[]=new byte[2];          
              byte version[]=new byte[2];
              byte uniqueID[]=new byte[4];
              byte cardFlag[]=new byte[1];
              byte cardSpecificType[]=new byte[2];
              byte reservedForOthers[]=new byte[5];
              public byte[] getCardFlag() {
                   return cardFlag;
              public void setCardFlag(byte[] cardFlag) {
                   this.cardFlag = cardFlag;
              public byte[] getCardSpecificType() {
                   return cardSpecificType;
              public void setCardSpecificType(byte[] cardSpecificType) {
                   this.cardSpecificType = cardSpecificType;
              public byte[] getCardtype() {
                   return cardtype;
              public void setCardtype(byte[] cardtype) {
                   this.cardtype = cardtype;
              public byte[] getReservedForOthers() {
                   return reservedForOthers;
              public void setReservedForOthers(byte[] reservedForOthers) {
                   this.reservedForOthers = reservedForOthers;
              public byte[] getUniqueID() {
                   return uniqueID;
              public void setUniqueID(byte[] uniqueID) {
                   this.uniqueID = uniqueID;
              public byte[] getVersion() {
                   return version;
              public void setVersion(byte[] version) {
                   this.version = version;
         class cardID1 implements Serializable
              char cardtype;          
              char version;
              int uniqueID;
              byte cardFlag;
              char cardSpecificType;
              byte reservedForOthers[]=new byte[5];
              public byte getCardFlag() {
                   return cardFlag;
              public void setCardFlag(byte cardFlag) {
                   this.cardFlag = cardFlag;
              public char getCardSpecificType() {
                   return cardSpecificType;
              public void setCardSpecificType(char cardSpecificType) {
                   this.cardSpecificType = cardSpecificType;
              public char getCardtype() {
                   return cardtype;
              public void setCardtype(char cardtype) {
                   this.cardtype = cardtype;
              public byte[] getReservedForOthers() {
                   return reservedForOthers;
              public void setReservedForOthers(byte[] reservedForOthers) {
                   this.reservedForOthers = reservedForOthers;
              public int getUniqueID() {
                   return uniqueID;
              public void setUniqueID(int uniqueID) {
                   this.uniqueID = uniqueID;
              public char getVersion() {
                   return version;
              public void setVersion(char version) {
                   this.version = version;
         }both the above classes have a memory capacity of 16 bytes as you are expecting and can be wriiten as object to file or String etc

  • DBMS_LOB.WRITE fails to write multi-byte data

    We have Oracle 8.1.6 database, UTF8, and a table with a CLOB column. I'm trying to write some multi-byte data (Japanese) to that CLOB using DBMS_LOB.WRITE(lob_loc,48,1,v_buffer);
    I get ORA-00600: internal error code, arguments: [711], [25806920], [koklt2u buf], [], [], [], [], []
    The data I'm trying to insert is UTF8 encoded(because I selected it from another table in the same database).
    Do I need to convert it to a multi-byte fixed width Unicode encoding to store in CLOB? I thought this would happen automatically.
    The DBMS_LOB.WRITE seemed worked OK when I wrote extended ASCII chars to the CLOB, but doesn't work for Japanese.
    null

    I think this is related to Bug 745585 - If the database char character set is varying-width, and you call DBMS_LOB.WRITE() with an input amount that is greater than the data in the buffer, you will get an internal error. The workaround is to provide the correct amount of data in the buffer.

  • Java.sql.SQLException  with  byte [ ]

    Hello,
    in a table of database Ms Access is one field has type OLE Object
    I want to write an query to query the file
    String val="arabicString";
    String QUERY="";
    Query +== "SELECT MyField FROM MyTable ""
    ="WHERE MyField="+val.getBytes("UTF-8") ";
    but I becom an Exception
    [Microsoft][ODBC Microsoft Access Driver] missing Element, ) o ] in query
    'MyField =[B@17725c4'.
    thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    String query = "SELECT MyField FROM MyTable WHERE MyField=(" + val.getBytes("UTF-8") + ")";
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Fehlendes Element, ) oder ] in Abfrageausdruck 'ArLastname=([B@12cc95d)'.
         at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
         at SQLFactory.getQuickSearchResults(SQLFactory.java:236)
         at TopicCreator.executeSearchAction(TopicCreator.java:975)
         at TopicCreator.actionPerformed(TopicCreator.java:893)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    String query = "SELECT MyField FROM MyTable WHERE MyField=[" + val.getBytes("UTF-8") + "]";
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Unzul?ssiges Einklammern des Namens '[[B@4f80d6]'.
         at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
         at SQLFactory.getQuickSearchResults(SQLFactory.java:236)
         at TopicCreator.executeSearchAction(TopicCreator.java:975)
         at TopicCreator.actionPerformed(TopicCreator.java:893)
         at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
         at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
         at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at javax.swing.JComponent.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Window.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • Java program to receive byte from serial port

    hello everyone, i am recently working one a project which require communication between pic16f877 and PC. My pic continuiously measure a voltage and send the result (a byte ranging from 0 to 255) to the rs232 port. One the pc side, my java program keep reading the serial port and it works for values 0~127 and 160~255. But if the byte value is between 127 and 160, it cannot received correctly, i get something like 375,8224,or even 65532 etc(no obvious path but more likely to be 300+,700+,8000+ or 65500+). I have been trying very hard to solve this and i think the problem is due to the pc software. I am feeling so frustrated and any suggestion will be much appreciated.
    p.s. : i used Bufferedreader.read() in my program
    --mengyao                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    fumengyao wrote:
    hello everyone, i am recently working one a project which require communication between pic16f877 and PC. My pic continuiously measure a voltage and send the result (a byte ranging from 0 to 255) to the rs232 port. One the pc side, my java program keep reading the serial port and it works for values 0~127 and 160~255. But if the byte value is between 127 and 160, it cannot received correctly, i get something like 375,8224,or even 65532 etc(no obvious path but more likely to be 300+,700+,8000+ or 65500+). I have been trying very hard to solve this and i think the problem is due to the pc software. I am feeling so frustrated and any suggestion will be much appreciated.
    p.s. : i used Bufferedreader.read() in my program
    --mengyaothis may not matter in your case - but don't use a Reader, use a Stream (BufferedInputStream maybe)

  • Using JSP / Java to write/create an xml file

    I have been looking around the internet and in my books and I cannot find a good example of JAVA/JSP writing an XML file. I already have a recursive method that will generate the xml .. what's missing in my code now is how am i goin to append or write that xml string into an existing file..
    suppose i have this xml string
    String xmlString = "<?xml version="1.0"?><txn><test>this is just a test</test></txn>";
    FileOutputStream fos = new FileOutPutStream(C://files/sample.xml);
    now , how i will write the xmlString into sample.xml file...
    Any suggestions/ ideas/ tutorial links would be deeply appreciated.. thx!

    never mind.. my code is workin now..

  • Java applet writes to file on client, no signing necessary

    Hi,
    I wonder if this is a feature or bug:
    I download and execute in my browser an unsigned applet/jar myCharts.jar from server. The applet references classes from package org.jfree.chart, which are not packed in myCharts.jar downloaded from server, but are locally stored on client in jre/lib/ext/jfreechart.jar (and therefore JVM running the applet loads and uses these local classes from local jar).
    The applet can write the file to client disk without any problem using classes from locally loaded jfreechart.jar. If I merge both jars into a big one and load it through network, file write access is forbidden.
    I am using JRE 1.5.0.3 for Windows and default java_policy file with 2      permissions added:
    permission java.lang.RuntimePermission "accessDeclaredMembers";
    permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
    Is it a bug, or feature ?
    According to my opinion these 2 permissions should not result in applet ability to write files using locally loaded classes.
    Thanks for your answer
    Martin

    The following is a duplicate posting in reponse to similar question:
    http://forum.java.sun.com/thread.jsp?forum=4&thread=200482&start=0&range=30#735223
    In short, you cannot write to a server without help from servier-side software such as a servlet, cgi, ASP, etc.
    If you go with something like an Oracle database on your server, it's a non-issue because the seucirty aspects are taken care of for you.
    V.V.

  • Diifferent java apllications write to the same flat file database

    I have a variety of java applications that need to be able to write diagnostics to the same flat file database (containes just one file). Could somebody give me the pointers what is the best way to write my applications so that different application not need to worry about the updates in file?
    They should be able to write whenever they want.

    JavaFunda wrote:
    I have a variety of java applications that need to be able to write diagnostics to the same flat file database (containes just one file). Could somebody give me the pointers what is the best way to write my applications so that different application not need to worry about the updates in file?I guess my question would be: is it a file or a database (as in an RDB)?
    I think EJP's post was aimed at syncing writes to files (and he'll definitely tell me if I'm wrong : )), but it may be redundant if, in fact, your output is going to a database.
    Also, Java has some quite sophisticated logging applications (I believe log4j is quite popular; but there are others), which may serve your needs.
    Winston

Maybe you are looking for

  • I have installed Firefox, Mozilla - NPAPI 16.0.0.305 but Flash Player does not appear in my Plug-ins

    Firefox version is 35.0.1. Although I can play Flash content at some sites, others return messages such as "The Camtasia Studio video content presented here requires a more recent version of the Adobe Flash Player. If you are you using a browser with

  • How to write values to an array and call these to produce an xy graph

    Hi, Hopefully someone can help. I have attahced my VI. I am happy with how to write data to a file, which I have already done. The next thing I want to do, is write the pressure and acoustic values to an array for the duration of my testing (Testing

  • Abap Rfc External Debug from a Jco Client Connection

    Hi to all, i have developed a Java Application on Sap J2ee (SAP-JEE 7.01 SP6) , using the Jco2 integrated. I'm using direct connection , calling Custom Functions Module on  Abap Stack. I have a question about Abap Debugging: now i debug the abap func

  • Java call terminated by uncaught Java exception: java.lang.NullPointerExcep

    i have written this program of adding file items using wwsbr_api.add_item but, 1 declare 2 l_new_item_master_id number; 3 l_caid number := 53; 4 l_folder_id number := 50279; 5 begin 6 select c.id, f.id 7 into l_caid, l_folder_id 8 from portal.wwsbr_a

  • Stuck Icon

    Hi, I was just wondering if anyone could help me out: I was connected to a server a while ago, but the weird thing is when I disconnected the icon remained on my desktop. And I can't seem to get it off of my desktop. And its not like its actually the