Read/write bytes in unicode

I have the next piece of code:
String encryptionText = "\u4f45\ueb33\ua4ea\ufcd0\u9e52\u6faf\udcd8\u4aa6";
File inputText, outputText;
outputText = new File("outputCod.txt");
FileInputStream fin;
FileOutputStream fout;
String key, text;
byte[] bufText, bufKey;
fout = new FileOutputStream(outputText);
fout.write(encryptionText.getBytes("UTF-8"));
fout.close();
inputText = new File("outputCod.txt");
fin = new FileInputStream(inputText);
bufText = null;
bufText = new byte [(int)inputText.length()];
fin.read(bufText);
fin.close();
text = new String (bufText, "UTF-8");
At the end i want to have in text the same thing as in encryptionText. But I dont. In encrytionText I have "\u4f45\ueb33\ua4ea\ufcd0\u9e52\u6faf\udcd8\u4aa6" and in text I have "\u4f45\ueb33\ua4ea\ufcd0\u9e52\u6faf?\udcd8\u4aa6". Any idea where that "?" comes from? encryptionText.getBytes("UTF-8") and bufText have the same content in the end.

just_me_n wrote:
why are they not valid? aren't all valid? \u0000 to \uffff? it;s not quite binary i need to put intro string...i need to put into string any kind of \uxxxx.No, they are not all valid (in particular, the surrogate pair range is treated differently). You should not be putting binary data into a string, only character data.

Similar Messages

  • Read/Write file in Unicode (UTF-16)

    Hi, I have some issue to write a file in Unicode (UTF-16)
    I have to read a file with LabView, change some parameters and write the new data into the same file. The file uses Unicode UTF-16.
    I downloaded some library here: https://decibel.ni.com/content/docs/DOC-10153
    I can read the file, convert the data to UNI/ASCII/UNI, and then write the file. But when I open the new file with an editor like Notepad++ there are some unexpected characters at the end of the line.
    Even reading the file and writing exactly the same data doesn'not work.
    I attached an example.
    Thanks for you kind support.
    Solved!
    Go to Solution.
    Attachments:
    TEST.zip ‏7 KB

    Right-click on your Read and Write Text File functions.  There is an option to "Convert End Of Line".  Turn that off on both functions.
    As a side not, you don't need the Close File functions.  The Read and Write Text File functions will close the file if the file reference output is not wired.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Unable to read/write bytes using 9870 with cRio 9151

    Hi everyone,
    I'm currently having some problems trying to use 2 ports of module NI 9870. I'm unable to read bytes even if I try to send some datas (I always get a Timeout) and I'm also unable to write some datas( I can't see nothing on Hyperterminal).
    Please find enclosed a snapshot of my Fpga code.
    Regard,
    Nicolas Kaminski, Toulouse France
    Attachments:
    ReadBytes.jpg ‏93 KB
    WriteBytes.jpg ‏30 KB

    Hello,
    Can you give us some other details:
    Are you sure that you provide power to the 9870 module?
    Do you have tested your system with an example? (NI-987x Serial Loopback.lvproj)
    DO you get something through that loopback?
    Regards,
    Mathieu P. | Certified LabVIEW Associate Developer
    National Instruments France
    #adMrkt{text-align: center;font-size:11px; font-weight: bold;} #adMrkt a {text-decoration: none;} #adMrkt a:hover{font-size: 9px;} #adMrkt a span{display: none;} #adMrkt a:hover span{display: block;}
    Journées techniques : des fondamentaux aux dernières technologies pour la mesure et le contrôle/comm...

  • Converting byte[] to unicode , help needed.

    need help, folks.
    i need to convert byte[] to unicode in byte[] form
    say i already loaded bunch of data
    byte[] bytes = {........} //bunch array of bytesand i read in the bytes as a stream in the native form.
    ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
    InputStreamReader isr = new InputStreamReader(stream,"GB18030");how do i get the bytes back in unicode ? i've been trying all kinds of methods, but doesnt seems to get what i want. i'm novice programmer, someone pls guide me ? thx.

                String s ;
              StringBuffer buffer = new StringBuffer();
              try {
                   ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
                   InputStreamReader isr = new InputStreamReader(stream, "GB18030");
                   Reader in = new BufferedReader(isr);
                   int ch;
                   while ((ch = in.read()) > -1) {
                   buffer.append((char)ch);
                   in.close();
                   s = buffer.toString();
                   bytes = s.getBytes("UnicodeLittle");
                   out.write(bytes);
              } catch (IOException e) {
                   e.printStackTrace();
                   //return null;
              }ah, nvm, i found a better solution to it, i'm little confused before this. the code above works fine.
    well, thx alot.

  • InputStream - OutputStream: Reader - Writer

    What was not possible by InputStream & OutputStream that JAVA had to provide Reader and Writer. I have found out that if I use InputStream to read a Chinese HTML page, it reads it. I can create a copy of the same HTML page by using OutputStream, the data remaining un-affected. Then, why do I go for Reader and Writer?
    What happens if InputStream encounters some unicode charchters to be read? How does InputStream and OutputStream function internally?

    Well, you can go look at the source of InputStream/OutputStream.
    The reason we have Reader/Writer as well is because the streams don't deal with character encoding (or at least, they tried to and did it very badly). So you would normally use streams for dealing with binary data and reader/writer for dealing with character data. If you're using streams to copy a file and this file happens be be HTML with Chinese characters, this will work fine because you're just duplicating bytes. But if you try and use a stream to read this file into memory, you will have problems because it won't understand the Unicode characters in the file. In this case, you need to use a Reader and tell it what the character encoding of the file is.

  • Urgent!!! Need help in file read/write data to a serial port

    Hi,
    I really need someone's help in order for me to complete my project. I have attached a vi which I have taken from an example and integrate to my project. In the vi, I have managed to get the encoder counts using Ni 9411. I need to read/write that data from ni9411 to ni9870 without using any serial port as they are connected to a NI 9104 chasis. May I know whether I am correct in writing the data to my ni9870 port using the vi I have attached? Does anyone know how i can convert the number of counts to a 8-bit data/byte so that I can send the data through the RS232 port? I really need someone's help as I need to finished in 2 weeks time.
    I have also attached an vi on controlling the epos2 controller using instrument driver. Does anyone know how can i integrate this vi to the fpga vi (the one which I need to read/write data to 9870) as I need to send those data to control my epos2 controller.
    Please help me!!!
    Attachments:
    Encoder Position & Velocity (FPGA).vi ‏23 KB
    SINGLEMOTORMODIFIED.vi ‏17 KB

    Afai,
    As I allready suggested you here, call your local NI Office and ask for assistance!
    You really need assistence in a higher level that we can provide via the forums. Otherwise I don't see a chance for you to finish your project in time.
    1. Convert I32 to U8 to write it to the 9870 could be done like this:
    2. The vi to control the epos2.
    There is NO way ( absolutely NO way) to port this vi to FPGA. It's based on VISA calls, uses an event-structure, both are not available at the FPGA.
    The only thing you could do is to analyze the VI, the instruction set and design an FPGA vi which handles the specific instructions you would need.
    I have no experience with epos2 and I'm not 100% sure if this would work as you would like to use it. And doing this needs deep knowledge of LabVIEW, VISA, Instrument Drivers, the epos hardware, FPGA programming, and so on... 
    Christian

  • Blob for binary file, read/write problems

    Hi,
    I am relatively new to this type of development so apologies if this question is a bit basic.
    I am trying to write a binary document (.doc) to a blob and read it back again, constructing the original word file. I have the following code for reading and writing the file:
    private void save_addagreement_Click(object sender, EventArgs e)
    // Save the agreement to the database
    int test_setting = 0;
    // create an OracleConnection object to connect to the
    // database and open the connection
    string constr;
    if (test_setting == 0)
    constr = "User Id=royalty;Password=royalty;data source=xe";
    else
    constr = "User ID=lob_user;Password=lob_password;data source=xe";
    OracleConnection myOracleConnection = new OracleConnection(constr);
    myOracleConnection.Open();
    // create an OracleCommand object to hold a SQL statement
    OracleCommand myOracleCommand = myOracleConnection.CreateCommand();
    myOracleCommand.CommandText = "insert into blob_content(id, blob_column) values 2, empty_blob())";
    OracleDataReader myOracleDataReader = myOracleCommand.ExecuteReader();
    // step 2: read the row
    OracleTransaction myOracleTransaction = myOracleConnection.BeginTransaction();
    myOracleCommand.CommandText =
    "SELECT id, blob_column FROM blob_content WHERE id = 2";
    myOracleDataReader = myOracleCommand.ExecuteReader();
    myOracleDataReader.Read();
    Console.WriteLine("myOracleDataReadre[\"id\"] = " + myOracleDataReader["id"]);
    OracleBlob myOracleBlob = myOracleDataReader.GetOracleBlobForUpdate(1);
    Console.WriteLine("OracleBlob = " + myOracleBlob.Length);
    myOracleBlob.Erase();
    FileStream fs = new FileStream(agreement_filename.Text, FileMode.Open, FileAccess.Read);
    Console.WriteLine("Opened " + agreement_filename.Text + " for reading");
    int numBytesRead;
    byte[] byteArray = new byte[fs.Length];
    numBytesRead = fs.Read(byteArray, 0, (Int32)fs.Length);
    Console.WriteLine(numBytesRead + " read from file");
    myOracleBlob.Write(byteArray, 0, byteArray.Length);
    Console.WriteLine(byteArray.Length + " written to blob object");
    Console.WriteLine("Blob Length = " + myOracleBlob.Length);
    fs.Close();
    myOracleDataReader.Close();
    myOracleConnection.Close();
    This gives the following console output:
    myOracleDataReadre["id"] = 2
    OracleBlob = 0
    Opened D:\sample_files\oly_in.doc for reading
    56832 read from file
    56832 written to blob object
    Blob Length = 56832
    My write to file code is:
    private void save_agreement_to_disk_Click(object sender, EventArgs e)
    string filename;
    SaveFileDialog savedoc = new SaveFileDialog();
    if (savedoc.ShowDialog() == DialogResult.OK)
    filename = savedoc.FileName;
    // create an OracleConnection object to connect to the
    // database and open the connection
    OracleConnection myOracleConnection = new OracleConnection("User ID=royalty;Password=royalty");
    myOracleConnection.Open();
    // create an OracleCommand object to hold a SQL statement
    OracleCommand myOracleCommand = myOracleConnection.CreateCommand();
    myOracleCommand.CommandText =
    "SELECT id, blob_column " +
    "FROM blob_content " +
    "WHERE id = 2";
    OracleDataReader myOracleDataReader = myOracleCommand.ExecuteReader();
    myOracleDataReader.Read();
    Console.WriteLine("myOracleDataReader[id] = " + myOracleDataReader["id"]);
    //Step 2: Get the LOB locator
    OracleBlob myOracleBlob = myOracleDataReader.GetOracleBlobForUpdate(1);
    Console.WriteLine("Blob size = " + myOracleBlob.Length);
    //Step 3: get the BLOB data using the read() method
    byte[] byteArray = new byte[500];
    int numBytesRead;
    int totalBytes = 0;
    FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write);
    while ((numBytesRead = myOracleBlob.Read(byteArray, 0, 500)) > 0)
    totalBytes += numBytesRead;
    fs.Write(byteArray, 0, byteArray.Length);
    Console.WriteLine("numBytes = " + numBytesRead + " totalBytes = " + totalBytes);
    Console.WriteLine((int)fs.Length + " bytes written to file");
    fs.Close();
    myOracleDataReader.Close();
    myOracleConnection.Close();
    This gives the following console output:
    myOracleDataReader[id] = 2
    Blob size = 0
    0 bytes written to file
    If I manually add the blob file using the following:
    DECLARE
    my_blob BLOB;
    BEGIN
    -- load the BLOB
    my_bfile := BFILENAME('SAMPLE_FILES_DIR', 'binaryContent.doc');
    SELECT blob_column
    INTO my_blob
    FROM blob_content
    WHERE id = 1 FOR UPDATE;
    DBMS_LOB.FILEOPEN(my_bfile, dbms_lob.file_readonly);
    DBMS_LOB.LOADFROMFILE(my_blob, my_bfile, DBMS_LOB.GETLENGTH(my_bfile), 1, 1);
    DBMS_LOB.FILECLOSEALL();
    COMMIT;
    END;
    COMMIT;
    The write to file works perfectly. This tells me that there must be something wrong with my code that is writing the blob to the database. I tried where possible to following the Oracle article using large objects in .NET but that (along with most things on the internet) focus on uploading text files.
    Thanks in advance.
    Chris.

    myOracleCommand.CommandText = "insert into blob_content(id, blob_column) values 2, empty_blob())";
    OracleDataReader myOracleDataReader = myOracleCommand.ExecuteReader();
    This looks wrong, you shouldn't be using ExecuteReader unless you expect to get a result back. Try using ExecuteNonQuery to do the insert.

  • How to write to file Unicode characters

    I have PDF files that I need to copy some strings out of and put them in various fields in a Postgres database. The goal is a Java screen into the database, whiere I mark and copy the PDF text and then paste it into a field in a Swing window, and from there into the database.
    I am unsuccessful at reading a PDF file, so I have opted to cut and paste the PDF file into an MS word file. This results in errors in certain unicode characters. I am trying to rectify them by a simple program, a start of which is below, by a replacement of the erroneous char by the proper unicode symbol. As, shown by the following, I cannot figure out how to write out a unicode character. Do I need to wrap (which I don't know much about yet)? Or do I have a file problem? (I have a Vista machine.) I don't think it should be impossible to write unicode into a file, as I am able to write into MS Word files phonological symbols, Russian, and Sanskrit. So, it must be in the java.
    P.S.: I am reading Schildt's Java: A Beginner's Guide and am through chapter10, but remaining chapters are on threads, enumerations, autoboxing, static import, annotations; generics,; applets, events, and miscellaneous topics, and, finally Swing. Maybe its in the autoboxing?
    Any help would be most appreciated.
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.PrintWriter;
    import java.io.IOException;
    public class CopyCharacters {
    public static void main(String[] args) throws IOException {
    FileReader inputStream = null;
    //FileWriter outputStream = null;
    PrintWriter outputStream = null;
         char longa = 0x0101;
         int longc = 0x0101;
         char capA = 0x0041;
         char longb = 0x0111;
    // Unicode for uppercase Greek omega character char uniChar = '\u039A'
         char uniChar = '\u039A';
    // Character ca = new Character('0x0101'); // illegal
         Character cb = new Character('\u0101');
         Character cc = '\u0101';
    int c;
    try {
    inputStream = new FileReader("Cardona1.txt");
    outputStream = new
                   PrintWriter(new FileWriter(
                        "characteroutput.txt"));
              outputStream.println( "character1 " + capA); //yields A
              outputStream.println( "character2 " + longa); //yields ?
              outputStream.println( "character3 " + '\u0101'); //yields ?
              outputStream.println( "character4 " + longc); //yields 257
              outputStream.println( "character5 " + "S\u00ED Se\u00F1or"); // yields character Sí Señor
              outputStream.println( "character6 " + "S'\u00ED' Se\u00F1or"); // yields S'í' Señor
              outputStream.println( "character7 " + "S\u0121 Se\u00F1or"); // yields character S? Señor
              outputStream.println( "character8 " + "S'\u0121' Se\u00F1or"); // yields character S'?' Señor
              outputStream.println( "character9 " + uniChar);// yields character ?
              outputStream.println( "character10 " + '\u00FF');// yields character ÿ but fails on \u0100.
    // only 0-255!!
              outputStream.println( "character11 " + cc);// yields ?
              outputStream.println( "character12 " + cb);// yields ?
              outputStream.println( "character13 ?");// yields ?
    while ((c = inputStream.read()) != -1) {
         // outputStream.writeln(c);- error
    } finally {
    if (inputStream != null) {
    inputStream.close();
    if (outputStream != null) {
    outputStream.close();
    }

    I am unsuccessful at reading a PDF file, so I have opted to cut and paste the PDF file into an MS word file. This results in errors in certain unicode characters.Stop right there. You are digging a hole. Stop digging. Fix the problems with reading the PDF file.

  • File transfer, read write through sockets in client server programming java

    Hello All, need help again.
    I am trying to create a Client server program, where, the Client first sends a file to Server, on accepting the file, the server generates another file(probably xml), send it to the client as a response, the client read the response xml, parse it and display some data. now I am successful sending the file to the server, but could not figure out how the server can create and send a xml file and send it to the client as response, please help. below are my codes for client and server
    Client side
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    public class XMLSocketC
         public static void main(String[] args) throws IOException
              //Establish a connection to socket
              Socket toServer = null;
              String host = "127.0.0.1";     
              int port = 4444;
              try
                   toServer = new Socket(host, port);
                   } catch (UnknownHostException e) {
                System.err.println("Don't know about host: localhost.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to host.");
                System.exit(1);
              //Send file over Socket
            //===========================================================
            BufferedInputStream fileIn = null;
              BufferedOutputStream out = null;
              // File to be send over the socket.
              File file = new File("c:/xampp/htdocs/thesis/sensorList.php");
              // Checking for the file to be sent.
              if (!file.exists())
                   System.out.println("File doesn't exist");
                   System.exit(0);
              try
                   // InputStream to read the file
                   fileIn = new BufferedInputStream(new FileInputStream(file));
              }catch(IOException eee)
                   System.out.println("Problem, kunne ikke lage fil");
              try
                   InetAddress adressen = InetAddress.getByName(host);
                   try
                        System.out.println("Establishing Socket Connection");
                        // Opening Socket
                        Socket s = new Socket(adressen, port);
                        System.out.println("Socket is clear and available.....");
                        // OutputStream to socket
                        out = new BufferedOutputStream(s.getOutputStream());
                        byte[] buffer = new byte[1024];
                        int numRead;
                        //Checking if bytes available to read to the buffer.
                        while( (numRead = fileIn.read(buffer)) >= 0)
                             // Writes bytes to Output Stream from 0 to total number of bytes
                             out.write(buffer, 0, numRead);
                        // Flush - send file
                        out.flush();
                        // close OutputStream
                        out.close();
                        // close InputStrean
                        fileIn.close();
                   }catch (IOException e)
              }catch(UnknownHostException e)
                   System.err.println(e);
            //===========================================================
            //Retrieve data from Socket.
              //BufferedReader in = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
              DataInputStream in = new DataInputStream(new BufferedInputStream(toServer.getInputStream()));
              //String fromServer;
            //Read from the server and prints.
              //Receive text from server
              FileWriter fr = null;
              String frn = "xxx_response.xml";
              try {
                   fr = new FileWriter(frn);
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              try{
                   String line = in.readUTF();                    //.readLine();
                   System.out.println("Text received :" + line);
                   fr.write(line);
              } catch (IOException e){
                   System.out.println("Read failed");
                   System.exit(1);
            in.close();
            toServer.close();
    public class XMLSocketS
          public static void main(String[] args) throws IOException
              //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4444);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
              while (true)
                        try
                             clientLink = serverSocket.accept();
                           System.out.println("Server accepts");
                             BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             // close the link to client
                             clientLink.close();                         
                             // close InputStream
                             inn.close();                         
                             // flush
                             ut.flush();                         
                             // close OutputStream
                             ut.close();     
                             //Sending response to client     
                             //============================================================
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
    }

    SERVER
    import java.net.*;
    import java.io.*;
    public class XMLSocketS
          public static void main(String[] args) throws IOException
                   //Establish a connection to socket
               ServerSocket serverSocket = null;
                 try {
                     serverSocket = new ServerSocket(4545);
                 } catch (IOException e) {
                     System.err.println("Could not listen on port: 4444.");
                     System.exit(1);
              Socket clientLink = null;
                  try
                             clientLink = serverSocket.accept();
                         System.out.println("Server accepts the client request.....");
                         BufferedInputStream inn = new BufferedInputStream(clientLink.getInputStream());
                             BufferedOutputStream ut = new BufferedOutputStream(new FileOutputStream(new File("c:/xampp/htdocs/received_from_client.txt")));
                             byte[] buff = new byte[1024];
                             int readMe;
                             while( (readMe = inn.read(buff)) >= 0)
                             {     //reads from input stream, writes the file to disk
                                  ut.write(buff, 0, readMe);
                             ut.flush();                         
                             //Sending response to client     
                             //============================================================
                             BufferedInputStream ftoC = null;
                             BufferedOutputStream outtoC = null;
                             // File to be send over the socket.
                             File file = new File("c:/xampp/htdocs/thesis/user_registration_response.xml");
                             try
                                  // InputStream to read the file
                                   ftoC = new BufferedInputStream(new FileInputStream(file));
                             }catch(IOException eee)
                             {System.out.println("Problem reading file");}
                             // OutputStream to socket
                             outtoC = new BufferedOutputStream(clientLink.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int noRead;
                             //Checking if bytes available to read to the buffer.
                             while( (noRead = ftoC.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  outtoC.write(buffer, 0, noRead);
                             outtoC.flush();
                             //============================================================
                             System.out.println("File received");
              }catch(IOException ex)
              {System.out.println("Exception.");}
                        finally
                             try
                                  if (clientLink != null) clientLink.close();
                             }catch(IOException e) {}
                 clientLink.close();
                 //serverSocket.close();
          }CLIENT SIDE
    import java.io.*;
    import java.net.*;
    public class XMLSocketC
              @SuppressWarnings("deprecation")
              public static void main(String[] args)
                   // Server: "localhost" here. And port to connect is 4545.
                   String host = "127.0.0.1";          
                   int port = 4545;
                   BufferedInputStream fileIn = null;
                   BufferedOutputStream out = null;
                   // File to be send over the socket.
                   File file = new File("c:/xampp/htdocs/thesis/sensorList.xml");
                   try
                        // InputStream to read the file
                        fileIn = new BufferedInputStream(new FileInputStream(file));
                   }catch(IOException eee)
                   {System.out.println("Problem");}
                   try
                             System.out.println("Establishing Socket Connection");
                             // Opening Socket
                             Socket clientSocket = new Socket(host, port);
                             System.out.println("Socket is clear and available.....");
                             // OutputStream to socket
                             out = new BufferedOutputStream(clientSocket.getOutputStream());
                             byte[] buffer = new byte[1024];
                             int numRead;
                             //Checking if bytes available to read to the buffer.
                             while( (numRead = fileIn.read(buffer)) >= 0)
                                  // Writes bytes to Output Stream from 0 to total number of bytes
                                  out.write(buffer, 0, numRead);
                             // Flush - send file
                             out.flush();
                             //=======================================
                             DataInputStream in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
                             BufferedWriter outf = new BufferedWriter(new FileWriter("c:/xampp/htdocs/received_from_server.txt",true));
                             String str;
                             while(!(str = in.readLine()).equals("EOF")) {     
                                  System.out.println("client : Read line -> <" + str + ">");
                                  outf.write(str);//Write out a string to the file
                                  outf.newLine();//write a new line to the file (for better format)
                                  outf.flush();
                             //=======================================
                             // close OutputStream
                             out.close();
                             // close InputStrean
                             fileIn.close();
                             // close Socket
                             clientSocket.close();
                        }catch (IOException e)
                        {System.out.println("Exception.");}
         Could you please point where am I doing the stupid mistake, client to server is working properly, but the opposite direction is not.
    Thanks

  • Asynchronous read & write by using Asynchronous api provided in nio-java 7

    HI,
    I am trying to write a small program to implement **asynchronous read & write by using Asynchronous api provided in nio in java 1.7** in windows machine.
    i tried the following code to write a small string to a file asynchronously.file is getting created but the contents are not dispalying.
         static long startTime = System.currentTimeMillis();
         static long endTime;
         static long execTime;
         public static void main(String[] args) {
              String path = "C:\\AsynchWrite.txt";
              Path file = Paths.get(path);
              final AsynchronousFileChannel channel;
              long pos = 1;
              try {
                   OpenOption[] options = { StandardOpenOption.CREATE,
                             StandardOpenOption.WRITE, StandardOpenOption.SYNC };
                   channel = AsynchronousFileChannel.open(file, options);
                   ByteBuffer buffer = ByteBuffer.allocate(1000);
                   String writeThis = "Testing by writing a line";
                   byte[] src = writeThis.getBytes();
                   buffer.put(src);
                   channel.write(buffer, pos, null,
                             new CompletionHandler<Integer, Object>() {
                                  @Override
                                  public void completed(Integer result, Object attachment) {
                                       System.out.println("completed successfully");
                                       System.out.println("start time :" + startTime);
                                       endTime = System.currentTimeMillis();
                                       System.out.println("end time : " + endTime);
                                       execTime = endTime - startTime;
                                       System.out.println("Execution Time :" + execTime);
                                       System.out.println("Execution Time(ms) :"
                                                 + execTime);
                                       try {
                                            channel.force(true);
                                            channel.close();
                                       } catch (IOException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                  @Override
                                  public void failed(Throwable exc, Object attachment) {
                                       // TODO Auto-generated method stub
                                       System.out.println("failed!!");
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         }Please help me out
    Thanks in advance,
    Ravi

    It looks like you are missing buffer.flip() after your put as otherwise the buffer position will be at 25 (not 0 as you expect).

  • Difference in read/write between Windows Vs Linux

    Hi,
    Can you please write, whether it is a bug or my ignorance. I thought, if a java program runs in Windows then it will run in other platform too, without editing any code. It proved me wrong. So is it a bug?
    Ref: Fedora linux version 5
    Kernel ver. 2.6.17
    jdk version - build 1.5.0_06-b05
    I was working on a web service. The server side program connects to an application using socket program and sends back data to client.
    While it was working very fine with Windows XP. When I moved the service to Linux (above said linux). The program stopped working. When I explored it, I found 3 things.
    1. I was using PrintWriter
    PrintWriter outputStream = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
    to write into the socket. It works fine in Windows but not in Linux. ie. it sends different bytes in linux. Thus fails. When I changed it to BufferedOutputStream it works fine.
    BufferedOutputStream outputStream = new BufferedOutputStream (socket.getOutputStream());
    2. I was using BufferedReader to read
    BufferedReader inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    data from socket. It reads. But byte varies from expectation. The same program works very well with windows.
    I used DataInputStream now. that works. but..
    DataInputStream inputStream = new DataInputStream(socket.getInputStream());
    3. While reading it was suppossed to read 2098 bytes, instead it reads 1448 bytes. It reads correctly in Windows, but not in the above said linux.
    Is it a bug or there is a difference in reading and writing from socket between Windows and Linux ( even though it is same JVM).
    Thanks
    Sasi.

    Thanks a lot for both of you.
    I believe, \r\n Vs \n could not be the reason.
    Because, I was sending binary data.Then you should not be using Writer at all!
    >
    With regard to "utf-8", I thought of that but I did
    not try to issue it in the function. Because, I was
    trying to send and receive raw binary data.Then you should not be using Writer at all!
    >
    Now, You may ask that why did you use PrintWriter.
    Because, the data had unsigned byte values. Makes no difference - you should not be using Writer at all!
    So I
    converted everything in to char array and send it.Will cause you problems at some point on some platform unless you use Base64 or HEX encoding.
    especially, whereever unsigned byte was required, I
    used (byte & Oxff). It worked very well with
    Windows. So I just go ahead doing other things.I use byte & 0xff for dealing with unsigned valued but your use sounds dangerous.
    >
    Here my question is, I assumed that if a program is
    written in java and complied on jvm x, then
    irrespective of the underlying OS, if the jvm is the
    same x, then the program should run without error. Is
    it wrong. If it is not wrong, then is it a jre bug?Your program will work if you have not used any implicit or explicit platform dependencies. For example, if in your program then you have hard codes a path as "C:\Program Files" then it will work on Windows (but then only if it has a C drive) but not on Unix.
    Any program has to deal with a number of platform specific features and Java protects you from them as much as possible BUT you must deal with things like Locale, EOL and default character encoding.
    No! Of course it is not a jre bug. You have coded to a specific platform and are then are suprised when it fails on other platforms.
    >
    Did you see my third point of my original problem
    statement. How to solve that.Since I don't have a view of your code I can't make an informed comment. I think I can guess what the problem is but I won't speculate.

  • Read / write cluster array?

    Hi NG,
    is there an easy way to read and write an array of clusters? I've found
    neither anything like that in my literature nor in the internet.
    I't would be great if someone could help me!
    Greetings
    Florian

    Hi,
    you must use "Read File.vi" and "Write File.vi" to read/write array of clusters to the file.
    When you write data to the file, you just need to wire your array to "data" input node of "Write File.vi". Also you may wire TRUE to "header" input of this VI. The header with array sizes will be added to the file so you will be able to read array back as an array, not as elements. Read help about this.
    When you read data from the file, you need to wire the array of cluster constant to "byte stream type" input of "Read File.vi" to specify the type of data which will be read from file.
    Also there are some examples in LabVIEW which could help you. Go to menu "Help->Examples...->Fundamentals->File I/O->Datalog File Examples"
    Good luck.
    Oleg Chutko.

  • SGA size is 1 GB  free but oracle starts physical read/write,why ?

    Dear Friends ,
    In my production server I observe that it takes the the data from the HDD where my SGA is still 1 GB free .
    As far I know , In oracle , when the allocated SGA size is filled up then it reads the data from the HDD which is called "physical read/write " . I am using oracle 10g database . In performance tab(From Oracle 10g OEM) , when I see that oracle starts to read the physical data , at that moment I run the following query :
    select sum(bytes)/1024/1024 " SGA size used in MB"
    from v$sgastat
    where name!='free memory';
    and I found that still 1 GB memory are still free in the SGA .
    In this moment , I want to know , is it possible to start the physical read / write while the SGA size are still free ?
    Edited by: shipon_97 on Mar 24, 2009 10:45 AM

    shipon_97,
    Your understanding is wrong. From your previous posts it appears you never read the concepts manual.
    Begging on my knees PLEASE READ IT and stop asking doc questions.
    Sybrand Bakker
    Senior Oracle DBA

  • Correct way to read/write ASCII data

    Hi,
    I am trying to read in ASCII data, manipulate it and write out as ASCII, but am getting values greater than 256 appearing. SHould I be using an encoding when I read/write and what is it.
    Any advice appreciated.
    MArk

    Smart quotes aren't part of the ASCII character set. If your character set includes them, it is possibly one of the so-called "extended ASCII" character sets that were created by various entities a few years ago. Java uses the Unicode character set, which includes ASCII as its first 128 characters. And the so-called smart quotes are mapped to the Unicode characters 201C ("LEFT DOUBLE QUOTATION MARK") and 201D. For more information about Unicode see http://www.unicode.org and for much more information on character sets in computing see for example http://www.czyborra.com.

  • FileWriter to write bytes

    Hi can I use the FileWriter class to write bytes arrays int a file or its exclusive for text?
    I used to use the common output streams (DATA and FILE) but for the appending issue I want to use the FileWriter. So, will it write correctly bytes instead of text?

    Hi can I use the FileWriter class to write bytes
    arrays int a file or its exclusive for text?For text.
    >
    I used to use the common output streams (DATA and
    FILE) but for the appending issue I want to use the
    FileWriter. So, will it write correctly bytes instead
    of text?Not really!

Maybe you are looking for

  • Can i share itunes library between separate user accounts?

    i bought a new imac and i am in the process of migrating from my pc. I have transferred my itunes library into my user account on my imac from my old windows computer. I have 3 other user accounts on my imac that i would like to be able to access the

  • Ncomp'ed code is SLOW

    Hi there, we have a JSP which converts text to PDF reading the text from a database CLOB. It works fine but is slow. We have the successfully ncomp'ed the code but found the JSP being even 10% slower then before. That is a surprise since we actually

  • Installing Acrobat Pro 11 and it stops and says close Safari, bat it is not open. //

    installing Acrobat Pro 11 on my Mac and it stops and says to close Safari, but Safari is not open???

  • Not able to boot to Windows XP all the time

    My BIOS version is AMIBIOS Version 3.31a. After installing a new hard drive with a K8T Neo-FSR motherboard am I receiving the following error. PXE-M0F: No boot filename received It keeps on doing the same error over and over again. The BIOS does see

  • Error with Partition Help please.

    Hello! So when I tried to install Windows on my Mac using Boot Camp Assistant, I set my partiton memory to 25 gigs (I have 150 gigs free) and clicked partition. However it said that it couldent be partitioned because some files couldent be moved. I r