String to CharBuffer

Hi @all i'm new in the world of Java,
but i have a problem to convert a String into CharBuffer. I wrote a programm that send info over network using Sockets. To send is no problem but to read, i became the message that i have to convert String into CharBuffer. I really don't know if it is possible. Thank you for the help.
The code is:
import java.net.*;
import java.io.*;
import java.nio.CharBuffer;
public class ADatenClient {
public static void main(String args[]){
Socket server = null;
int BallX;
int BallY;
int SchlgX;
int SchlgY;
BallX = balla.getBall_x_pos();
BallY = balla.getBall_y_pos();
Schlaeger Schl2 = new Schlaeger;
SchlgX = Schl2.getSchl_x_pos();
SchlgY = Schl2.getSchl_y_pos();
try{
server = new Socket("localhost", 50000);
InputStream in = server.getInputStream();
OutputStream out = server.getOutputStream();
OutputStreamWriter out1 = new OutputStreamWriter(out);
OutputStreamWriter out2 = new OutputStreamWriter(out);
OutputStreamWriter out3 = new OutputStreamWriter(out);
OutputStreamWriter out4 = new OutputStreamWriter(out);
out1.write("<ballx>"+Integer.toString(BallX)+"</ballx>");
out2.write("<bally>"+Integer.toString(BallY)+"</bally>");
out3.write("<schlaegerx>"+Integer.toString(SchlgX)+"</schlaegerx>");
out4.write("<schlaegery>"+Integer.toString(SchlgY)+"</schlaegery>");
InputStreamReader in1 = new InputStreamReader(in);
InputStreamReader in2 = new InputStreamReader(in);
InputStreamReader in3 = new InputStreamReader(in);
InputStreamReader in4 = new InputStreamReader(in);
/*in1.read("<ballx>"+CharBuffer.wrap(BallX)+"</ballx>");
in2.read("<bally>"+CharBuffer.wrap(BallY)+"</bally>");
in3.read("<schlaegerx>"+CharBuffer.wrap(SchlgX)+"</schaegerx>");
in4.read("<schlaegery>"+CharBuffer.wrap(SchlgY)+"</schaegery>");
}catch(UnknownHostException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
finally{
if(server != null)
try{
server.close();
} catch(IOException e){
e.printStackTrace();
}

Thank for answer.
I put it so:
CharBuffer     BalX;
in1.read("<ballx>"+BalX.wrap(String.valueOf(BallX).toC
harArray() +"</ballx>");
And Eclipse says : The method read(CharBuffer) in the
type Reader is not applicable for the arguments
(String)
I have no idea, what can i do.
Thank you!what about:
in1.read(BalX.wrap(("<ballx>" + BallX + "</ballx>").toCharArray() );but heck, I'm no expert in this area...

Similar Messages

  • Creating String frm new String(charBuffer.array()) Vs charBuffer.toString()

    Whats the difference in creating String from CharBuffer by using array and by using toString() ?
    When ever i have some UTF-8 chars in my file (""someFile"), String created from new String( charBuffer.array()) appends some extra null/junk charaters at the very end of the file.
    How ever when i try charBuffer.toString() its working fine.
    For simple ASCII i.e ISO-*** charset both methods are working fine.
    Please see below code for reproducing. Here "someFile" is any text file with some UTF-8 characters.
    public char[] getCharArray()
    throws IOException
    Charset charset = Charset.forName("UTF-8");
    CharsetDecoder decoder = charset.newDecoder();
    FileInputStream fis = new FileInputStream("someFile");
    FileChannel channel = fis.getChannel();
    int size = (int) channel.size();
    MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_ONLY, 0 , size);
    CharBuffer cb = decoder.decode(mbb);
    channel.close();
    fis.close();
    return cb.array();
    public String getAsString()
    throws IOException
    Charset charset = Charset.forName("UTF-8");
    CharsetDecoder decoder = charset.newDecoder();
    FileInputStream fis = new FileInputStream("someFile");
    FileChannel channel = fis.getChannel();
    int size = (int) channel.size();
    MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_ONLY, 0 , size);
    CharBuffer cb = decoder.decode(mbb);
    channel.close();
    fis.close();
    return cb.toString();
    String fromToString = getAsString();
    String fromCharArray = new String(getCharArray());

    Whats the difference in creating String from CharBuffer by using array and by using toString() ?array() returns the entire backing array regardless of offset and position. toString() takes those into account.
    When ever i have some UTF-8 chars in my file (""someFile"), String created from new String( charBuffer.array()) appends some extra null/junk charaters at the very end of the file.More probably you haven't filled the array.
    How ever when i try charBuffer.toString() its working fine.So there you go.

  • CharsetDecoder is blank

    Whenever I use the CharsetDecoder to decode a ByteBuffer, it returns the correct number of characters, but they are all blank. I can decode the bytebuffer by casting individual bytes to ascii, but this is kludgy and inefficient.
    I am wondering if this is a bug in java.nio.charset.* or am I doing something wrong?
    I am having problems with the following code snippet:
    public String decode( ByteBuffer byteBuffer )
    throws CharacterCodingException {
    //FIXIT there is a problem with the decoder in version beta2
    // because it returns null characters for us-ascii
    Charset charset = Charset.forName( "us-ascii" );
    CharsetDecoder decoder = charset.newDecoder();
    decoder.reset();
    CharBuffer charBuffer = decoder.decode( byteBuffer );
    decoder.flush( charBuffer );
    String result = charBuffer.toString();
    log.debug( result );
    return result;

    The problem here is that following a read of a buffer, one must use the buffer.flip() method.
    Following a read on from the channel, the buffer must ready for a get operation. Here is an example:
    int nbytes = channel.read( byteBuffer );
    byteBuffer.flip();

  • NIO and object serialization

    I try to use the new IO API to implement a non-blocking multi-threaded server that communicates with client applications by exchanging serialized objects. I started from the code in the JavaWorld article at http://www.javaworld.com/javaworld/jw-09-2001/jw-0907-merlin.html .
    With the new features of J2SDK 1.4.0, you don't have to create a separate thread per connected client. That is a big improvement.
    But when I read an object with ObjectInputStream, I get a java.nio.channels.IllegalBlockingModeException.
    Has anybody successfully implemented such a server since the release of the new io API?
    Thanks.
    Jean-Robert

    Hi,
    I tried to decode it and reconstruct the object as follows:
    buffer.flip();
    // Decode buffer
    decoder.decode(buffer, charBuffer, false);
    // Display
    charBuffer.flip();
    String str = charBuffer.toString();
    try
         ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
         ObjectInputStream ois = new ObjectInputStream(bis);
         Object obj = ois.readObject();
         if (obj != null)
         System.out.println(obj.getClass().getName());
         System.out.println("Construction successful");
    catch (Exception e)
         e.printStackTrace();
    I think it is constructing the object. But it gave me the following exception:
    java.io.InvalidClassException: MessageValueObject; local class incompatible: stream classdesc serialVersionUID = -1062950779601993928, local class serialVersionUID = -1038743931604855240
         at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:454)
         at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1511)
         at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1425)
         at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1616)
         at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1264)
         at java.io.ObjectInputStream.readObject(ObjectInputStream.java:322)
         at com.csxwt.zodiac.client.common.NIOPushletClient.run(NIOPushletClient.java:254)
         at java.lang.Thread.run(Thread.java:536)
    Whe I compared the bytes of returned object with the actual object I noticed that two bytes were different from the orignal. They were replaced with '?' (byte code 063) in the reconstructed byte stream.
    If anybody have a clue please help me too

  • NIO Non-Blocking Server not Reading from Key

    I have created a NIO non blocking server (below) and it will not pick up any input from the client.... My log doesnt even show that it enters the readKey() method, so it must be something before. Any help would be appreciated.
    Scott
    package jamb.server;
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.ClosedChannelException;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.spi.SelectorProvider;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.logging.Logger;
    import java.util.prefs.Preferences;
    import jamb.server.client.Client;
    public class Server {
            private Selector selector;
            private ServerSocketChannel serverChannel;
            private static Logger logger = Logger.getLogger("jamb.server");
            private static Preferences prefs =  Preferences.systemRoot().node("/jamb/server");
            public void init() {
                    logger.entering("jamb.server.Server", "init");
                    //Get a selector...
                    try {
                            selector = SelectorProvider.provider().openSelector();
                            //Open the SocketChannel and make it non-blocking...
                            serverChannel = ServerSocketChannel.open();
                         serverChannel.configureBlocking(false);
                            //Bind the server to the port....
                            int port = prefs.getInt("Port", 4000);
                            logger.config("Server configured on port " + port + " (default: 4000)");
                         InetSocketAddress isa = new InetSocketAddress(
                                    InetAddress.getLocalHost(), port);       
                         serverChannel.socket().bind(isa);
                    } catch (IOException ioe) {
                            logger.severe ("IOException during server initialization!");
                    logger.exiting("jamb.server.Server", "init");
            public void run() {
                    logger.entering("jamb.server.Server", "run");
                    int bufferSize = prefs.getInt("BufferSize", 8);
                    logger.config("Buffer size set to " + bufferSize + " (default: 8)");
                    SelectionKey acceptKey = null;
                    try {
                            acceptKey = serverChannel.register(
                                    selector, SelectionKey.OP_ACCEPT);
                    } catch (ClosedChannelException cce) {
                    try {
                            while (acceptKey.selector().select() > 0) {
                                    Set readyKeys = selector.selectedKeys();
                                    Iterator i = readyKeys.iterator();
                                    while (i.hasNext()) {
                                            //logger.finest("Processing keys...");
                                            //Get the key from the set and remove it
                                            SelectionKey currentKey = (SelectionKey) i.next();
                                            i.remove();
                                            if (currentKey.isAcceptable()) {
                                                    logger.finest("Accepting key...");
                                                    acceptKey(currentKey);
                                            } else if (currentKey.isReadable()) {
                                                    logger.finest("Reading key...");
                                                    readKey(currentKey, bufferSize);
                                            } else if (currentKey.isWritable()) {
                                                    //logger.finest("Writing key...");
                                                    writeKey(currentKey);
                    } catch (IOException ioe) {
                            logger.warning("IOException during key handling!");
                    logger.exiting("jamb.server.Server", "run");
            public void flushClient (Client client) {
                    try {
                            ByteBuffer buf = ByteBuffer.wrap( client.getOutputBuffer().toString().getBytes());
                            client.getChannel().write(buf);
                    } catch (IOException ioe) {
                            System.out.println ("Error writing to player");
                    client.setOutputBuffer(new StringBuffer());
            private void acceptKey (SelectionKey acceptKey) {
                    logger.entering("jamb.server.Server", "acceptKey");
                    //Retrieve a SocketChannel for the new client, and register a new selector with
                    //read/write interests, and then register
                    try {
                            SocketChannel channel =  ((ServerSocketChannel) acceptKey.channel()).accept();
                            channel.configureBlocking(false);
                            SelectionKey readKey = channel.register(
                                    selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE  );
                            readKey.attach(new Client(this, channel));
                    } catch (IOException ioe) {
                            System.out.println ("Error accepting key");
                    logger.exiting("jamb.server.Server", "acceptKey");
            private void readKey (SelectionKey readKey, int bufSize) {
                    logger.entering("jamb.server.Server", "readKey");
                    Client client = (Client) readKey.attachment();
                    try {
                            ByteBuffer byteBuffer = ByteBuffer.allocate(bufSize);
                            int nbytes = client.getChannel().read( byteBuffer );
                            byteBuffer.flip();
                            Charset charset = Charset.forName( "us-ascii" );
                            CharsetDecoder decoder = charset.newDecoder();
                            CharBuffer charBuffer = decoder.decode(byteBuffer);
                            String text = charBuffer.toString();
                            client.getInputBuffer().append(text);
                            if ( text.indexOf( "\n" ) >= 0 )
                                    client.input();
                    } catch (IOException ioe) {
                            logger.warning("Unexpected quit...");
                            client.disconnect();
                    logger.exiting("jamb.server.Server", "readKey");
            private void writeKey (SelectionKey writeKey) {
                    //logger.entering("jamb.server.Server", "writeKey");
                    Client client = (Client) writeKey.attachment();
                    if (!client.isConnected()) {
                            client.connect();
                    //logger.exiting("jamb.server.Server", "writeKey");

    From my own expierence with the NIO (Under Windows XP/ jdk1.4.1_01); you can't seem to set READ and WRITE at the same time.
    The program flow I usually end up with for a echo server is:
    When the selector.isAcceptable(): accept a connection; register for READs
    In the read event; write the incoming characters to a buffer; register for a WRITE and add the buffer as an attachment.
    In the write event; write the data to the socket If all the data was written; register for a READ; otherwise register for another WRITE so that you can write the rest.
    Not sure if that the "proper" way; but it works well for me.
    - Chris

  • Sockets in non-blocking mode

    Hello Techies,
    How to set sockets in the non-blocking mode and what is the main use of setting sockets in non-blocking mode.
    regards,
    Ramu.

    Hello Techies,
    Thanks for u r replies,
    Finally i had understood how to use nio. But the problem is it is going into infinite loop. Here is my code.
    package networking;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.CharBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.nio.charset.Charset;
    import java.nio.charset.CharsetDecoder;
    import java.util.Iterator;
    public class testSocketChannel {
          * @param args
         public static ByteBuffer buf ;
         public static SocketChannel clientChannel;
         public static void main(String[] args) {
              // TODO Auto-generated method stub
                        try
                             Selector selector = Selector.open();
                         clientChannel = SocketChannel.open();
                      clientChannel.configureBlocking(false);
                      // Send a connection request to the server; this method is non-blocking
                      clientChannel.connect(new InetSocketAddress("localhost",90));
                      clientChannel.register(selector,clientChannel.validOps());
    //                Wait for events
                      while (true)
                          try {
                              // Wait for an event
                              selector.select();
                          } catch (IOException e) {
                              // Handle error with selector
                              //break;
                          // Get list of selection keys with pending events
                          Iterator it = selector.selectedKeys().iterator();
                          // Process each key at a time
                          //while (it.hasNext())
                               for(int i = 0;i<selector.selectedKeys().size();i++)
                              // Get the selection key
                              SelectionKey selKey = (SelectionKey)it.next();
                              // Remove it from the list to indicate that it is being processed
                              it.remove();
                              try
                          //  processSelectionKey(selKey);
                                    if (selKey.isValid() && selKey.isConnectable()) {
                                       // Get channel with connection request
                                       SocketChannel sChannel = (SocketChannel)selKey.channel();
                                       boolean success = sChannel.finishConnect();
                                       if (!success) {
                                           // An error occurred; handle it
                                           // Unregister the channel with this selector
                                           selKey.cancel();
                                   if (selKey.isValid() && selKey.isReadable()) {
                                       // Get channel with bytes to read
                                        clientChannel = (SocketChannel)selKey.channel();
                                       System.out.println("INSIDE reading");
                                       // See e174 Reading from a SocketChannel
                                       // Clear the buffer and read bytes from socket
    //                                 Clear the buffer and read bytes from socket
                                      // ByteBuffer byteBuffer = ByteBuffer.allocate( BUFSIZE );
                                       buf = ByteBuffer.allocateDirect(1024);
                                       int nbytes = clientChannel.read( buf );
                                       buf.flip();
                                       Charset charset = Charset.forName( "us-ascii" );
                                       CharsetDecoder decoder = charset.newDecoder();
                                       CharBuffer charBuffer = decoder.decode( buf );
                                       String result = charBuffer.toString();
                                   if (selKey.isValid() && selKey.isWritable()) {
                                       // Get channel that's ready for more bytes
                                       //SocketChannel sChannel = (SocketChannel)selKey.channel();
                                       System.out.println("INSIDE writting");
                                       // See e175 Writing to a SocketChannel
                                     String message = "hi"; 
                                      buf = ByteBuffer.wrap( message.getBytes()  );
                                       int nbytes = clientChannel.write( buf );
                                       System.out.println( "Wrote " + nbytes + " to channel." );
                              catch (IOException e) {
                                       // TODO: handle exception
                                   System.out.println("IOException"+e.getMessage());
                        catch (IOException ioe) {
                             // TODO: handle exception
                             System.out.println("IOException"+ioe.getMessage());
    }How to stop this infinite loop.
    Need quick replies.
    Ramu

  • Why it don't work?

    I have two classes in diffrent files and in the same package.In first file I have
    package KomunikatorArtka;
    public class Klient{
    public void nasluchuj() throws java.io.IOException {
    ObslugaXML parsowanie=new ObslugaXML(doCharBuffer(wiad));
    public CharBuffer doCharBuffer(ByteBuffer bytebuff){
    CharBuffer charbuff=CharBuffer.allocate(rozmiar);
    Charset ascii=Charset.forName(kodowanie);
    charbuff=ascii.decode(bytebuff);
    charbuff.flip();
    String wiad=charbuff.toString();
    return charbuff;
    and in second
    package KomunikatorArtka;
    public class ObslugaXML{
    public ObslugaXML(CharBuffer polaczenie){
    wiad=polaczenie.toString();
    t=new Thread();
    t.start();
    When i try to compile my package jva throw
    "Klient.java": Error #: 300 : constructor ObslugaXML(java.nio.CharBuffer) not found in class komunikatorartka.ObslugaXML at line 84, column 33

    I discover something
    public class ObslugaXML extends DefaultHandler implements Runnable {
    String odKogo="";
    boolean inMessage,inBody;
    String typ,wiad;
    private Thread t;
    //1
    ObslugaXML(java.nio.CharBuffer tekst){
    wiad=tekst.toString();
    t=new Thread();
    t.start();
    //2
    In JBuilder when write class and after dot JBuilder shows methods and fields from this class.So when I write java.nio.CharBuffer in 1 I see methods from ObslugaXML and I write java.nio.CharBuffer in 2 it shows what it should

  • ByteBuffer and file copy

    Hi all,
    I have implemented a copyFile method using ByteBuffer and Channel, the method works correclty and so ah yeah!
    NOW
    I would like to modify that method to do a encrypted copy of file source, that is:
    during the read/write cycle using ByteBuffer I have to encrypt source byte array and put it in the ByteBuffer in order that the output file results encrypted
    Now, my original code is this:
    while (in.read(buffer) != -1) {                  
      buffer.flip();
      out.write(buffer);
      buffer.clear();
    }     The final code, where I have problem, should is like this:
    while (in.read(buffer) != -1) {                  
      buffer.flip();
      // Prepare a byte array
      byte[] bytes = new byte[bbuf.limit()];               
      // Retrieve bytes from ByteBuffer
      bbuf.get(bytes);
      // My personal method to encrypt a byte array
      String encryptedStr = SecurityUtils.getInstance().encode(bytes); 
      // NOW WHAT HAVE I DO WITH THIS STRING?
      out.write(buffer);
      buffer.clear();
    }     I tried to write after the above upper case comment this line:
    bbuf.put(encryptedStr.getBytes());
    but it didn't work!
    Can you help me please to solve this problem?
    Thank you very much.
    Raffaele

    You need to make use of Charset for encoding and decoding while converting between string and bytes.
    Here is an example...
    // Create the encoder and decoder
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetDecoder decoder = charset.newDecoder();
    CharsetEncoder encoder = charset.newEncoder();
    try
    // Convert string to bytes (ISO-LATIN-1) in ByteBuffer
    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("string"));
    // Convert bytes from ByteBuffer into CharBuffer and then to a string.
    CharBuffer cbuf = decoder.decode(bbuf);
    String s = cbuf.toString();
    catch (CharacterCodingException e) {
    }For more info and sample code, please visit [http://everydaydeveloper.blogspot.com/2009/03/java-buffers.html]

  • Problems with nio decoder need help plz

    I want to make a flash/php chat Client with Java Server with the new nio.
    Problem is to Convert a Bytebuffer into a normal string.
    I done this with the charsetdecoder and it works...
    if i give the string with system.println out it will be the right string. but i cant use the string with the if method..
    my source:
    php:
    $nick="Nerrik";
    $host = "localhost";
    $data="-".$nick.";$REMOTE_ADDR";
    $fp = fsockopen($host,1120);
    fwrite($fp, $data,strlen($data));
    fclose($fp);
    java:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.nio.*;
    import java.nio.channels.*;
    import java.nio.charset.*;
    public class newserver
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetDecoder decoder = charset.newDecoder();
    CharsetEncoder encoder = charset.newEncoder();
    ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
    CharBuffer charBuffer = CharBuffer.allocate(1024);
    String[] user=new String[100];
    String[] user2=new String[100];
    private Selector readSelector;
    public void start() throws Exception
    System.out.println("Server Gestartet...");
    System.out.println("Protokoll aktiv");
    SocketChannel client;
    readSelector=Selector.open();
    ServerSocketChannel channel=ServerSocketChannel.open();
    ServerSocket socket=channel.socket();
    socket.bind(new InetSocketAddress ("localhost",1120));
    channel.configureBlocking(false);
    while (true)
    client=channel.accept();
    if (client!=null)
    client.configureBlocking(false);
    client.register(readSelector,SelectionKey.OP_READ);
    handleClientRequest();
    public void handleClientRequest() throws Exception
    Set keys;
    Iterator it;
    SelectionKey key;
    SocketChannel client;
    if (readSelector.selectNow()>0)
    keys=readSelector.selectedKeys();     
    it=keys.iterator();
    while(it.hasNext())
    key=(SelectionKey)it.next();
    if(key.isReadable())
    client=(SocketChannel)key.channel();
    buffer.clear();
    charBuffer.clear();
    client.read(buffer);
    buffer.flip();
    decoder.decode(buffer, charBuffer, false);
    charBuffer.flip();
    String em = charBuffer.toString();
    String aktion = em.substring(0,1);
    if(aktion=="-")
    //this don't come and em.substring(0,1) is -
    StringTokenizer st = new StringTokenizer(em,";");
    System.out.println("New Client:"+st.nextToken()+" on IP:"+st.nextToken());
    client.close();
    public static final void main(String args[]) throws Exception
    (new newserver()).start();
    sorry for my bad bad english ;)

    The code segment...
    if(aktion=="-")
    //this don't come and em.substring(0,1) is -
    StringTokenizer st = new StringTokenizer(em,";");
    System.out.println("New Client:"+st.nextToken()+" on IP:"+st.nextToken());
    will always return false. You are comparing the object reference of aktion to "-". The code should read:
    if(aktion.equals("-"))
    //this don't come and em.substring(0,1) is -
    StringTokenizer st = new StringTokenizer(em,";");
    System.out.println("New Client:"+st.nextToken()+" on IP:"+st.nextToken());
    The reason why it works when you hard code the values is because the Java comiler will only keep one object for each String literal. Thus:
    String aTest = "test";
    aTest=="test"; // This will return true but
    String aTest = getStringFromWhereElseThatIsTest();
    aTest=="test"; // Will most likely return false
    - Chris

  • Replace the text numbers string in a txt file using C++.. Help Me..

    Read a Document and replace the text numbers in a txt file using c++..
    For ex: 
    Before Document: 
    hai hello my daily salary is two thousand and five and your salary is five billion. my age is 
    twenty-five. 
    After Document: 
    hai hello my daily salary is # and your salary is #. my age is #. 
    All the text numbers and i put the # symbol.. 
    I am trying this code: 
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    ifstream myfile_in ("input.txt");
    ofstream myfile_out ("output.txt");
    string line;
    void find_and_replace( string &source, string find, string replace ) {
    size_t j;
    for ( ; (j = source.find( find )) != string::npos ; ) {
    source.replace( j, find.length(), replace );
    myfile_out << source <<endl;
    cout << source << endl;
    int main () {
    if (myfile_in.is_open())
    int i = 0,j;
    //string strcomma ;
    // string strspace ;
    while (! myfile_in.eof() )
    getline (myfile_in,line);
    string strcomma= "two";
    string strspace = "#";
    find_and_replace( line , strcomma , strspace );
    i++;
    myfile_in.close();
    else cout << "Unable to open file(s) ";
    system("PAUSE");
    return 0;
    Please help me.. Give me the correct code..

    Open the file as a RandomAccessFile. Check its length. Declare a byte array as big as its length and do a single read to get the file into RAM.
    Is this a simple text file (bytes)? No problem. If it's really 16-bit chars, use java.nio to first wrap the byte array as a ByteBuffer and then view the ByteBuffer as a CharBuffer.
    Then you're ready for search/replace. Do it as you would in any other language. Be sure to use System.arraycopy() to shove your bytes right (replace bigger than search) or left (replace smaller than search).
    When done, a single write() to the RandomAccessFile will put it all back. As you search/replace, keep track of size. If the final file is smaller than the original, use a setLength() to the new size to avoid extraneous data at the end.

  • Convert String from UTF-8 to IsoLatin1

    Hi everyone !
    I'm trying to convert a String from utf-8 to IsoLatin1, but i got somt problems.... I'm using
    actually this code, but it won't work...
    I'm getting a utf-8 html String with some data and i will write it down in latin1 to a text file
    String newString = new String(oldString.getBytes("UTF-8"), "ISO-8859-1");If i'm now writing this newString to a TextFile it contains cryptic signs like
    & # 1 3 ; or & # 1 3 7 ; or & # 1 2 8 ;(i separated this chars)
    can anyone tell me where is my fault and how can i solve this problem ?
    Thanks a lot
    Edited by: Sephiknight on Feb 23, 2008 2:41 AM

    Yes its XML, i got a web editor where i can add input (utf-8) and i want to write it down in my class to a xml file (isoLatin1).
    My code looks likte this
         public static void setEditFragment(String content, String xPath) throws Exception {
             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
             DocumentBuilder builder  = factory.newDocumentBuilder();
             Document document = builder.parse("3001300.xml");
             XPath xpath = XPathFactory.newInstance().newXPath();
             Node node = (Node)xpath.evaluate(xPath, document, XPathConstants.NODE);
            Charset charset = Charset.forName("ISO-8859-1");
            CharsetEncoder encoder = charset.newEncoder();    
            ByteBuffer buf = encoder.encode(CharBuffer.wrap(content));
            node.setTextContent(buf.toString()); 
               // Use a XSLT transformer for writing the new XML file
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
             DOMSource        source = new DOMSource( document );
             FileOutputStream os     = new FileOutputStream("tmp.xml");
             StreamResult     result = new StreamResult( os );
             transformer.transform( source, result ); 
         }The example from http://www.exampledepot.com/egs/java.nio.charset/ConvertChar.html looks great, but if I add my own input string i get a exception that looks like this
    java.nio.charset.UnmappableCharacterException: Input length = 1
         at java.nio.charset.CoderResult.throwException(Unknown Source)
         at java.nio.charset.CharsetEncoder.encode(Unknown Source)
         at HagerAbs.setEditFragment(HagerAbs.java:91)
         at HagerAbs.main(HagerAbs.java:108)When i write my input to the xml file it doesnt look like xml at all, it looks more like
    <synthese>& # 13;
    & # 13;
    & lt;br/& gt;& # 13;
    & lt;img class="thumb" src="http: ......{code}
    (i seperated the char so you can see)
    and this is not what i expected... how can i write it down correctly ?
    Edited by: Sephiknight on Feb 23, 2008 3:26 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • CharBuffer view on ByteBuffer and No Bytes Written to SocketChannel

    Hi,
    I've actually got two problems that might be connected. I'm new to the java.nio.* package. I wanted to try SocketChannel's to see if I could improve performance.
    If this isn't the appropriate place for java.nio questions, just let me know.
    My first problem is that I create a ByteBuffer by allocating x number of bytes. These bytes are the length of the message I want to send to the server. Then, I attempt to get a CharBuffer view of the ByteBuffer (buffer.asCharBuffer). For some reason, it only returns a CharBuffer with half the capacity of the ByteBuffer. So of course, when I stuff my String into the CharBuffer, it doesn't fit.
    Well, I hack that and make the ByteBuffer twice as big. Which brings me to problem two, my SocketChannel does not write any bytes to the server when told to.
    Here's the code (with hack):
              ByteBuffer buf;
              CharBuffer cbuf;
              SocketChannel sockChan;
              try {
                   int msgLength = message.length();
                   logger.info("Message length=" + msgLength);
                   logger.info("message length in bytes=" + message.getBytes().length);
                   buf = ByteBuffer.allocateDirect(msgLength*2);
                   logger.info("position=" + buf.position());
                   logger.info("capacity=" + buf.capacity());
                   logger.info("limit=" + buf.limit());
                   cbuf = buf.asCharBuffer();
                   logger.info("capacity of cbuf=" + cbuf.capacity());
                   cbuf.put(message);
                   buf.flip();
                   sockChan = SocketChannel.open();
                   sockChan.configureBlocking(true);
                   sockChan.socket().setSoTimeout(TIMEOUT_MS);
                   logger.info("socket configured");
                   sockChan.connect(new InetSocketAddress(ipAddress, portNumber));
                   int numBytesWritten = sockChan.write(buf);
                   logger.info("connected and wrote message. NumBytes writen=" + numBytesWritten);
                   if (numBytesWritten != msgLength) {
                        //throw error
                        logger.error("The number of bytes written do not match the " +
                             "message length (in bytes).");
              } catch (IOException e1) {
                   // TODO Auto-generated catch block
                   e1.printStackTrace();
              }And the console outputs the following:
    [Dec 13, 11:46:17] INFO - Message length=50
    [Dec 13, 11:46:17] INFO - message length in bytes=50
    [Dec 13, 11:46:17] INFO - position=0
    [Dec 13, 11:46:17] INFO - capacity=100
    [Dec 13, 11:46:17] INFO - limit=100
    [Dec 13, 11:46:17] INFO - capacity of cbuf=50
    [Dec 13, 11:46:17] INFO - socket configured
    [Dec 13, 11:46:17] INFO - connected and wrote message. NumBytes writen=0
    [Dec 13, 11:46:17] ERROR - The number of bytes written do not match the message length (in bytes).My batch program freezes at this point. Don't know why it does that either.
    Thanks for any help,
    CowKing

    ByteBuffer (buffer.asCharBuffer). For some reason, it
    only returns a CharBuffer with half the capacity of
    the ByteBuffer.The reason is simply that chars are twice as big as bytes, so you can only get half as many of them into the same space. The capacity of a ByteBuffer is measured in bytes. The capacity of a CharBuffer is measured in chars. The capacity of a DoubleBuffer is measured in doubles.
    Well, I hack that and make the ByteBuffer twice as
    big. Which brings me to problem two, my SocketChannel
    does not write any bytes to the server when told to.As it says in the Javadoc for ByteBuffer, a view buffer has its own position, limit, and mark. When you put data into it the data goes 'through' into the underlying ByteBuffer but the revised position/limit do not. You have to do that yourself manually, remembering to multiply by two as above to account for the difference widths of chars and bytes.

  • How to avoid string copy when spliting the string?

    Hi all,
    I have some old APIs (which I do not have control over) that expects the caller to pass the "content" of a text file as either String or String[] (each element is a line in the text file). Since the text file can be huge, I want to save memory and try to only hold 1 copy of the file content in memory. So, the question boils down to how can I make a String variable and a String[] variable share one single piece of memory.
    After digging into the source code, I notice the String.substring(...) always makes allocate a new memory space for the returning string if the result substring is smaller than 1/4 of the actual String. The String.split() method internally also invokes the String.substring(...) method.
    This creates a problem for me. If I first load the content of a file into a String "a". Then I call "String[] array = a.split("\n")", as the result, each element in the resulting array will be a copy of the substring of the original String "a" (since each line in my text file will be smaller than 1/4 of the entire file). StringTokenizer seems to have the same problem. Is there anything else I could do?
    I really would like to extends the String class and override the substring method to make it always "share" the same memory content. But since String class is declared as final, I cannot do this. I think maybe the String.split() method implementation should make the return String[] from the split function share the same memory space as the original string. Any workaround anyone can suggest?
    Thanks
    -- Gary

    While you could try to create some sort of custom class, if you want something that is already in java, you need to use one of the instantiations of CharSequence
    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/CharSequence.html
    Personally, I would recommend CharBuffer. From the look of it, it seems most like what you want.
    Hi all,
    I have some old APIs (which I do not have control
    rol over) that expects the caller to pass the
    "content" of a text file as either String or String[]
    (each element is a line in the text file). Since the
    text file can be huge, I want to save memory and try
    to only hold 1 copy of the file content in memory.
    So, the question boils down to how can I make a
    a String variable and a String[] variable share one
    single piece of memory.
    After digging into the source code, I notice the
    the String.substring(...) always makes allocate a new
    memory space for the returning string if the result
    substring is smaller than 1/4 of the actual String.
    The String.split() method internally also invokes
    s the String.substring(...) method.
    This creates a problem for me. If I first load
    oad the content of a file into a String "a". Then I
    call "String[] array = a.split("\n")", as the result,
    each element in the resulting array will be a copy of
    the substring of the original String "a" (since each
    line in my text file will be smaller than 1/4 of the
    entire file). StringTokenizer seems to have the same
    problem. Is there anything else I could do?
    I really would like to extends the String class and
    nd override the substring method to make it always
    "share" the same memory content. But since String
    class is declared as final, I cannot do this. I
    think maybe the String.split() method implementation
    should make the return String[] from the split
    function share the same memory space as the original
    string. Any workaround anyone can suggest?
    Thanks
    -- Gary

  • Non-Blocking Writing and Strings

    Hello.
    My question is simple, is it possible to write strings using a non-blocking method?
    I was praying that there was a method in the NIO API that allowed me to, yet i can't find one.
    If the answer is blatantly obvious please forgive me, i'm tired and hungry :)
    Thank you for looking at this topic

    Strings are written to files or sockets using a certain encoding. I usually use UTF-8, but your application might be different.
    1. Get the SocketChannel from your non-blocking socket.
    SocketChannel ch = mySocket.getChannel(); // mySocket is java.net.Socket2. Make a CharBuffer out of the String you want to send.
    CharBuffer chars = CharBuffer.wrap(myString); // myString is your data3. Encode it so it becomes a ByteBuffer. I'll use the [UTF-8|http://www.joelonsoftware.com/articles/Unicode.html] Charset here.
    ByteBuffer bytes = Charset.forName("UTF-8").encode(chars);4. Use the write(ByteBuffer) method in the SocketChannel from 1.
    ch.write(bytes);Import declarations:
    import java.nio.channels.SocketChannel;
    import java.nio.CharBuffer;
    import java.nio.ByteBuffer;
    import java.nio.charset.Charset;s

  • Cannot assign an empty string to a parameter with JDBC type VARCHAR

    Hi,
    I am seeing the aforementioned error in the logs. I am guessing its happening whenever I am starting an agent instance in PCo. Can somebody explain whats going on?
    Regards,
    Chanti.
    Heres the complete detail from logs -
    Log Record Details   
    Message: Unable to retreive path for , com.sap.sql.log.OpenSQLException: Failed to set the parameter 1 of the statement >>SELECT ID, PARENTID, FULLPATH, CREATED, CREATEDBY, MODIFIED, MODIFIEDBY, REMOTEPATH, CHECKEDOUTBY FROM XMII_PATHS WHERE FULLPATH =  ?  <<: Cannot assign an empty string to a parameter with JDBC type >>VARCHAR<<.
    Date: 2010-03-12
    Time: 11:32:37:435
    Category: com.sap.xmii.system.FileManager
    Location: com.sap.xmii.system.FileManager
    Application: sap.com/xappsxmiiear

    Sounds like a UI browsing bug (when no path is selected from a catalog tree folder browser) - I would suggest logging a support ticket so that it can be addressed.

Maybe you are looking for

  • How to write file at server end?

    Hi, I use a af:inputFile component to receive uploaded files. And want to write files to the directory of server. However, when execute java.io.File.createNewFile(), it throw exception. How to resolve it? import org.apache.myfaces.trinidad.model.Uplo

  • Error when quitting After Effects

    Somtimes when I quit After Effects CS6 on my MacBook Pro (2.2 GHz i7 Processor, 6750M Radeon Graphics Card), I receive the following error message: After Effects Alert Last log message was: <140735189834080> <ae.blitpipe> <2> HardwareBlitpipe Disenga

  • Spellchecker in Mail how do i exit it ?

    Hi all, while using Mail on my MacBookPro i compose a new message and click SEND and it Checks the spelling and lets me correct it and then the Email gets sent. Quite often i am looking at the email while the spellchecker is on the screen doing its s

  • ITunes cutting off songs

    I have a music collection over 60 Gig on iTunes and I have been noticing lately that certain songs just cut off in the middle and skip to the next song. Now when I go back to the song that skipped I try to play it to the part it skipped and it is com

  • Can you report on aggregares? If so whats the scenario?

    Can you report on aggregares? If so whats the scenario?