Using DataOutputStream/DataInputStream

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

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

Similar Messages

  • Externalizable vs DataOutputStream/DataInputStream (Storable Interface)

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

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

  • DataOutputStream / DataInputStream   ( Losing information? )

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

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

  • Writing to a file using DataOutputStream

    the goal is to write an object named cd1 to a file data.dat using a method writeData.
    writeData is defined as:
    void writeData(DataOutputStream out), which writes an object, field y field to a DataOutputStream. (plus some other blah blah).
    so here's what I have so far (only pieces of code are posted)
    File dataFile = new File(ioDir, "data.dat");
                   dataFile.createNewFile();
                   DataOutputStream out1 = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile)));
                   cd1.writeData(out1);
         public void writeData(DataOutputStream out) {
              iWritten = true;
              try {
                   out.writeInt(iNumTracks);
                   out.writeBoolean(iWritten);
                   out.close();
              } catch (IOException xcp) {
                   System.out.println(xcp);
         }but when I open the file data.dat it seems to be totally empty, doesn't seem like anything gets written to it.

    have to check the file size ?
    the data you write to the file maybe not displayable on screen. example, all character/byte < 32

  • Multi-threaded performance server using 2 ports to two-way communication

    Hi, I'm new in the forums so welcome everyone. I'm developing now an online computer game based on orginal Polish board-game, but it doesn't mean. Important is that I need to develope a high-performance multi-threaded server, which can serve... let's say few hundres of games, and a thousend of players simulateously. My server works on two ports/sockets.
    First one is represented by "ServerSocketChannel clientConSsc" in my code. The main thread in my server class which invokes the method "run()" (which You can see below), registers clientConSsc with Selector and then repeatingly accepts incoming connections from clients on this socket. When connection(channel) is estabilished and clients wants to write some request to this channel, the main thread on server creates a new instance of class "RequestHandler" which extends Thread and handles this request (reads the request from channel, makes some changes on server, spreads some new messages to other clients in the same game and so on... everything on the same socket/port/channel). Then the channel/connection is closed by the server - I call such connections: "a short connections". In the same time the main thread continues the loop and is still able to accept connections from another players. That's the idea of multi-threaded server, right? :) And to this point, everything works fine, but... what if the server wants to trigger some new command, write new information to client?
    Server could have tried to open a SocketChannel to client's IP address, but then the client programme would have to create and ServerSocketChannel object, bind it to some InetAddress and then... and then client becomes a server! - that breaks the idea of client-server cooperation and demands on players of my game to have routed some port on their machines. To resolve this problem I made some sort of "system" which, when some player/client is logging into my server, accepts second (this time constant, not "short") connection on the second port I mentoined on the beginning. This connection is held in variable "SocketChannel serverCon" of class "Player" - which reflects a player logged onto server. Server maintains every such connection till the client logs off. After the connection is accepted, the player whom connection it was is added to collection called "playersToRegisterToWrite". After the Selector.selectNow() is invoked (as You can see in the code below), each and every player's connection is registered in selector (with selection key - OP_WRITE and attachment pointing on owning player). In the same time client's code is trying to read some bytes from this connection and blocks on it until some bytes are written to this connection. When server wants to "tell" something to client, deliver some message/command, it creates a new instance of class which extends an abstract class called "ServerAction" (another new thread) and adds it to collection "actionsToDo". In ServerAction's method "run()" there are whole code to interact with client (e.g. send an update of players' list, an update of games' list, a chat message). Finnaly when Selector informs the server that some connection is writable (some client is waiting for commands), then server checks if there's any "actionToDo" involving this client/player. If there is, it unregisters the connection from Selector (so no other ServerAction (thread) can write on this connection) and starts the action. At the end of every "run()" method of subclass of ServerAction there's a code, which again adds the player to collection "playersToRegisterToWrite", so the player's connection can again be registered in Selector and the player can again receive informations from server - after it consumed THIS "ServerAction".
    It looks to me like it should be working fine, but it's not. When I test my server and clients on the same machine (no ping/latency) everything seems to be working fine. But when it comes to play my game with somebody even on LAN or through the Internet there comes the problems. My first socket I describe (and first type of connections - short connections) works perfectly fine, so the requests triggered by client are delivered and handled properly. But the second socket is cirppling. For example: the server triggers a command refering to an update of clients logged to server' list. It is triggered by Selector so the client should be ready to read data from server, so the server sends data! And the client never receives it... Why?
    It experimented a whole lot of time on SocketChannel's method "configureBlocking(boolean)", but it never helps. I think the client should always block it's listening thread on connection, contratry to server which is ment to be fast, so it should send the data through non-blocking channels. Am I right? Are there any rules refering blocking configuration of SocketChannels?
    I will be grateful for every answer. To help You out I attach also drafts from run()'s methods of my classes.
    Server's main method - main thread :
        public void run() {
           try {
                selector = Selector.open();
                clientConSsc.configureBlocking(false);
                clientConSsc.register(selector , SelectionKey.OP_ACCEPT);
                while(serverRunning) {
                    try {
                        selector.selectNow();
                        Iterator it;
                        synchronized(playersToRegisterToWrite) {
                            it = playersToRegisterToWrite.iterator();
                            while(it.hasNext()) {
                                Player player = (Player)it.next();
                                it.remove();
                                player.serverCon.configureBlocking(false);
                                player.serverCon.register(selector , SelectionKey.OP_WRITE , player);
                        Set keys = selector.selectedKeys() {
                        it = keys.iterator();
                        while(it.hasNext()) {
                            SelectionKey key = (SelectionKey)it.next();
                            if(key.isAcceptable()) {
                                it.remove();
                                clientCon = clientConSsc.accept();
                                clientCon.configureBlocking(false);
                                clientCon.register(selector , SelectionKey.OP_READ);
                                continue;
                            if(key.isReadable()) {
                                it.remove();
                                key.cancel();
                                new RequestHandler(this , (SocketChannel)key.channel()).start();
                                continue;
                            if(key.isWritable()) {
                                if(key.attachment() != null ) {
                                    ServerAction action = null;
                                    synchronized(actionsToDo) {
                                        Iterator aIt = actionsToDo.iterator();
                                        while(aIt.hasNext()) {
                                            ServerAction temp = (ServerAction)aIt.next();
                                            if(temp.getPlayer().equals((Player)key.attachment())) {
                                                action = temp;
                                                aIt.remove();
                                                break;
                                    if(action != null) {
                                        key.channel().configureBlocking(false);
                                        it.remove();
                                        key.cancel();
                                        action.start();
                                continue;
                    } catch(Exception e) {
                        statusArea.append(e.toString() + "\n");
                        e.printStackTrace();
                        continue;
            } catch(ClosedChannelException e) {
                statusArea.append(e.toString() + "\n");
            } catch(IOException e) {
                statusArea.append(e.toString() + "\n");
                A part of server's RequestHandler's class' method run() - the method which handles requests triggered by client on first port:
    public void run() {
            boolean served = false;
                try {
                    channel.configureBlocking(true);
                    retryCount++;
                    retry = false;
                    String command = ns.readText(channel).trim();
                    ns.statusArea.append("ktos przesyla komende: " + command + "\n");
                    if(command != null && !command.equals("ERROR")) {
                        String[] cmd = command.split("�");
                        ns.statusArea.append("komenda: " + cmd[0] + "\n");
                        if(cmd[0].equals("CHAT")) {
                            if(cmd.length != 5) {
                                retry();
                            } else {
                                if(cmd[2].equals("NOGAME")) {      // jezeli nie ma okreslonej gry czyli rozsylamy do wszystkich
                                    for(int i = 0 ; i < ns.loggedPlayersListItems.size() ; i++) {
                                        Player current = (Player)ns.loggedPlayersListItems.get(i);
                                        if(current.state == Player.CHOOSING && !current.equals(new Player(Integer.parseInt(cmd[1]))))   // jezeli gracz jest w okienku wybierania gry to wysylamy mu broadcast
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                } else {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(new Game(Integer.parseInt(cmd[2]))));
                                    for(int i = 0 ; i < game.players.size() ; i++) {
                                        Player current = (Player)game.players.get(i);
                                        if(!current.equals(new Player(Integer.parseInt(cmd[1]))))
                                            ns.actionsToDo.add(new SendMsg(ns , current , "CHAT�" + cmd[1] + "�" + cmd[3] + "�" + cmd[4]));
                                served = true;
                        } else if(cmd[0].equals("GETGAMEINFO")) {
                            if(cmd.length != 3)
                                retry();
                            else {
                                int gameID = Integer.parseInt(cmd[2]);
                                ns.statusArea.append("poproszono o informacje o grze nr: " + gameID + "\n");
                                Game checkedGame = new Game(gameID);
                                if(ns.gamesListItems.contains(checkedGame)) {
                                    Game game = (Game)ns.gamesListItems.get(ns.gamesListItems.indexOf(checkedGame));
                                    channel.configureBlocking(true);
                                    ObjectOutputStream oos = new ObjectOutputStream(channel.socket().getOutputStream());
                                    oos.writeObject(game);
                                    oos.writeObject(game.players);
                                    oos.flush();
                                    ns.statusArea.append("wyslano informacje o grze nr: " + gameID + "\n");
                                } else {
                                    ns.statusArea.append("brak gry o nr: " + gameID + "\n");
                                served = true;
                } catch(IOException e) {
                    e.printStackTrace();
            if(!served) {
                ns.findAndDisconnectPlayer(channel);
            try {
                channel.close();
            } catch(IOException e) {
                e.printStackTrace();
        }An example of ServerAction's subclass - the class which triggers server commands to client on second port:
    class UpdateLoggedPlayersList extends ServerAction {
        public UpdateLoggedPlayersList(NeuroServer ns , Player player) {
            super(ns , player);
        public void run() {
            try {
                serverCon.configureBlocking(true);
                ns.sendText("UPDATELOGGEDPLAYERSLIST" , serverCon);
                if(ns.readText(serverCon).equals("OK")) {
                    ObjectOutputStream oos = new ObjectOutputStream(serverCon.socket().getOutputStream());
                    oos.writeObject(ns.loggedPlayersListItems);
                    oos.flush();
                synchronized(ns.playersToRegisterToWrite) {
                     ns.playersToRegisterToWrite.add(player);
            } catch(IOException e) {
                e.printStackTrace();
    }A part of client's CmdHandler's class' method run() - the method which handles commands triggered by server:
    public void run() {
        try {
            while(works) {
                String command = nc.readText(nc.serverCon);
                System.out.println("Server przesyla komende: " + command + "\n");
                String[] cmd = command.split("�");
                if(cmd[0] != null && !cmd[0].equals("ERROR")) {
                    if(cmd[0].equals("CHAT")) {
                        if(nc.chooseGameDialog != null && nc.chooseGameDialog.isVisible()) {     // jezeli na wybieraniu gry
                            newChatEntry(cmd[2] , null , cmd[3] , nc.chooseGameDialog.chatPane);
                        } else if(nc.readyDialog != null && nc.readyDialog.isVisible()) {  // jesli na przygotowywaniu
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.readyDialog.chatPane);
                        } else if(nc.ng != null) {                   // jesli w grze
                            Player sender = (Player)nc.actGame.players.get(nc.actGame.players.indexOf(new Player(Integer.parseInt(cmd[1]))));
                            newChatEntry(cmd[2] , sender.fraction , cmd[3] , nc.ng.inGameChatPane);
                    } else if(cmd[0].equals("UPDATELOGGEDPLAYERSLIST")) {
                        nc.sendText("OK" , nc.serverCon , false);
                        nc.serverCon.configureBlocking(true);
                        ObjectInputStream ois = new ObjectInputStream(nc.serverCon.socket().getInputStream());
                        DefaultListModel players = (DefaultListModel)ois.readObject();
                        nc.chooseGameDialog.updateLoggedPlayersList(players);
        } catch(IndexOutOfBoundsException e) {
            System.out.println(e);
        } catch(IOException e) {
            System.out.println(e);
        } catch(ClassNotFoundException e) {
            System.out.println(e);
    }And two methods I used in codes above: sendText(String text , SocketChannel sc) and readText(SocketChannel sc) - they are my "utility" methods, which I use to send and receive Strings through specified SocketChannels.
    boolean sendText(String text , SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        boolean sendRetry;
        boolean sent = false;
        do {
            sendRetry = false;
            try {
                StringBuffer cmd = new StringBuffer();
                cmd.setLength(0);
                if(text.length()+4 < 100)
                    cmd.append("0");
                if(text.length()+4 < 10)
                    cmd.append("0");
                cmd.append(Integer.toString(text.length()+4) + "�");
                cmd.append(text);
                cmd.append("\n");
                bbuf = charset.encode(CharBuffer.wrap(cmd));
                sc.write(bbuf);
                bbuf.clear();
                int n = sc.read(bbuf);
                if(n == 1) {
                    bbuf.flip();
                    Byte re = bbuf.get();
                    if(re == 1) {
                        sendRetry = true;
                    } else {
                        sent = true;
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return false;
        } while(!sent && sendRetry);
        return true;
    String readText(SocketChannel sc) {
        ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
        int readRetryCount = -1;
        boolean readRetry;
        do {
            readRetry = false;
            readRetryCount++;
            StringBuffer cmd = new StringBuffer();
            cmd.setLength(0);
            bbuf.clear();
            try {
                readLoop:
                while(true) {
                    int n = sc.read(bbuf);
                    if(n > 0) {
                        bbuf.flip();
                        CharBuffer cbuf = charset.decode(bbuf);
                        while(cbuf.hasRemaining()) {
                            char c = cbuf.get();
                            if(c == '\r' || c == '\n') break readLoop;
                            cmd.append(c);
                    } else break;
                statusArea.append(Thread.currentThread().getId() + " readText() odczytuje: " + cmd.toString() + "\n");
                if(cmd.length() < 3 || Integer.parseInt(cmd.substring(0 , 3)) != cmd.length()) {
                    sc.write(ByteBuffer.wrap(new byte[] {1}));
                    readRetry = true;
                } else {
                    sc.write(ByteBuffer.wrap(new byte[] {0}));    // length OK
                    return cmd.toString().substring(4 , cmd.toString().length());
            } catch(Exception e) {
                findAndDisconnectPlayer(sc);
                try {
                    sc.close();
                } catch(IOException f) {
                    f.printStackTrace();
                return "ERROR";
        } while(readRetry && readRetryCount < 3);
        findAndDisconnectPlayer(sc);
        try {
            sc.close();
        } catch(IOException e) {
            e.printStackTrace();
        return "ERROR";
    }Edited by: Kakalec on Jul 23, 2008 11:04 AM

    You seem to be using a horrendous mixture of PrintWriters, BufferedReaders, ObjectOutputStreams, and no doubt ObjectInputStreams. You can't do that.
    Some rules about this:
    (a) Whenever you use a stream or reader or writer on a socket, you must allocate it once for the life of the socket, not every time you want to do an I/O.
    There are many reasons for this including losing buffered data in the old stream and auto-closure of the socket on garbage-collection of the old stream.
    (b) You can't mix stream types on the same socket. (i) If you're writing objects, use an ObjectOutputStream, you must read with an ObjectInputStream, and you can't read or write anything that isn't supported by the API of ObjectOutputStream. (ii) If you're writing lines, use a BufferedWriter and a BufferedReader at the other end. If you're writing characters, use a Writer and a Reader. (iii) If you're writing primitive data or UTF strings, use a DataOutputStream and a DataInputStream. (iv) If you're writing bytes, use DataOutputStream and a DataInputStream or an OutputStream and an InputStream. You can't mix (i), (ii), (iii), and (iv).
    (c) Don't use PrintWriter or PrintStream over the network. They swallow exceptions that you need to know about. They are for writing to the console, or log files, where you don't really care about exceptions.
    (d) Call flush() before reading.
    (e) Always close the 'outermost' output stream or writer of a socket, never the input stream or the socket itself. Closing any of these closes the socket and therefore makes the other stream unusable, but only closing the output stream/writer will flush it.

  • Need Detail about DataInputStream()

    Hi,
    While I try to get an input using DataInputStream() and print the same using DataOutputStream(), I get the different value. I read that these methods uses Unicode format to handle the data, I need more explanation. I gave 23 as input but it prints 50 as output what makes this differences .

    From the DataInputStream API documentation:
    "A data input stream lets an application read primitive Java data types
    from an underlying input stream in a machine-independent way. An
    application uses a data output stream to write data that can later be
    read by a data input stream."
    Read the second sentence again.
    First write your data to a data output stream, then (and only then)
    use a DataInputStream to read it.
    If you search about these forums you will find detailed explanations
    of what happens when you wrap System.in in this strange way. But,
    really, this is not what a DataInputStream is for.
    Check out http://forum.java.sun.com/thread.jspa?threadID=695548

  • Strange DataOutputStream file.

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

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

  • Using ByteArrayOutputStream then converting to a byte[]?

    Well, im making a little game and it uses a cache which is a data cache containing the information of other cache's inside.
    So for example, i could have the actual cache called;
    "main_cache_1" and inside it will be the data of;
    "sub_cache_1", "sub_cache_2".
    I read the names and length of the data, then read the data.
    So, say i want to edit part of the cache without leaving any of the include files exposed, i made a method to add data into it, basically it's DataInputStream using a byteArrayInputStream to read the data file inside, i can read it fine and then i use DataOutputStream and ByteArrayOutputStream to write what i want to change, so for example if i wanted to edit the name of a piece of data in the sub cache i would get the filebytes and then use the bytearray api to read.
    When the instream name is equal to what i want to edit, the outstream writes a different name, all the other time it writes what it reads, then after, i need to apply the bytearrayoutputstream to a normal byte[] so i can pack it into the data file with ease, but im not sure how to.
    I tried this;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    // Reading and writing in here
    byte[] newCache = baos.buf;But the buf is protected and does not let me use it, am i doing it wrong?
    I was thinking about doing this for example;
    DataInputStream newInput = new DataInputStream(new ByteArrayInputStream());
    byte[] newCache = new byte[baos.size()];
    baos.writeTo(newInput);
    newInput.readFully(newCache, 0, newCache.length);Do you think that would work?
    Thanks for any help.

    byte[] newCache = baos.toByteArray();
    http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html#toByteArray()
    -Puce

  • DataInputStream doubt

    import java.io.*;
    class first
         public static void main(String args[]) throws IOException
              FileOutputStream f1 = new FileOutputStream("Student1.txt");
              DataOutputStream dos1 = new DataOutputStream(f1);
              dos1.writeBytes("hi");
              dos1.writeChars("hello");
              f1.close();
              FileInputStream fis1 = new FileInputStream("Student1.txt");
              DataInputStream dis1 = new DataInputStream(fis1);
              //System.out.println(dis1.readBytes());
              //System.out.println(dis1.readChars());
              fis1.close();
    As you can see that i have written 2 strings "hi" and "hello" using writeBytes() and writeChars(). Now my problem is how can i read these strings using DataInputStream???? Please help

    it is ok that i can read/write using
    objectinput/output stream. But if i can write
    strings using dataoutputstream then there shouldbe
    some way of reading a string usingdatainputstream.Did you try writeUTF and readUTF?
    moreover can we read any data using
    g objectinputstream if it is written using
    dataoutputstream????? I doubt it. And even if you can today, I wouldn't
    rely on it continuing to work, unless the docs
    specifically state that you can.I am interested in finding out why you say that. The javadoc says:
    A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in.

  • Using API's

    Greetings,
    I am writing a project which needs to "read" data out of .pdb file (this file contains debugging information for VC++ 6 and .NET).
    Problem is - the intra structure and format of the .pdb file were not published by Microsoft, and they are not going to reveal it.
    However, they have supplied some API's, which extract data out of the .pdb file, which is enough for my needs (for example - names and location of the source files, symbols, etc.).
    All examples in MSDN are written in C++ (or C#), but not in Java. They are all include some header file (dia.h, or dia2.h, etc.), which contains structure used by those API's.
    Well, my question is - how do I use those API's? How do I get the structure of the data (from the .h files)? Can I do it, or must I build structures myself?
    Any assistance would by appreciated deeply.
    Kind regards,
    Ohad.

    If you have "cracked" the file format maybe based on the header files, you can use a
    DataInputStream to deal with it.
    Some time ago I sought for some pieces of information on the NT file system (NTFS). The documentation at some M$ developer site was referring to the documentation/source of the Linux NTFS driver.
    Good Microsoft (long may it live and reign!) is not keen on documenting...

  • TCP/IP DataInputStream reads not all data send in one time?

    I have a C program that sends 4104 bytes of data to a java client.
    In my java client I have a buffer of 4104 bytes that reads the data using a DataInputStream. Now my problem is that the read function returns with only 1460 bytes instead of 4104 bytes.
    I only have this problem on a new type of PC we are using.
    Now I was wondering when you have a TCP/IP session doesn't every send results in 1 recv (read)?
    Does this differ for various platforms? (is that buffer size adjustable)
    Thanks!

    Alright then I do have a problem.
    If your application level doesn't define a blockthen
    you have problems.So I have to keep reading on the socket untill I get a
    timeout? I saw that DataInputStream has a function
    available(), this should return the available number
    of bytes that can be read without blocking. This
    hardly seems to work?
    I just want to read 1 TCP packet without knowing the
    size or the protocol of the packet without having to
    wait for some timeout. I don't want to reassemble -
    defragmentate all my packets. This question seems very
    reasonable to me, but perhaps I'm missing something?
    There's no guarantee in TCP that a block size N
    written in one application will be delivered as a
    single block to the receiver.Is there a place I can read that specification?Usually people need to understand an API in order to be able to use it. TCP sockets present a continuous stream paradigm: the data stream starts when the connection is established and ends when the connection is closed. Now reread your own question: you want to read a block of data from such a stream without knowing the size of the block. That just makes no sense. It is like trying to read first X bytes from a file stream without actually knowing what X is. The number of bytes available immediately on a socket read is subject to all kinds of random factors on the network and has nothing to do with the amount of data the server is actually trying to send as a "block". That is, a single write() on the server does not necessarily correspond to a single read() on the client.
    A common solution to this problem is to have an implicit block size (that is, it is fixed and known apriory) or prefix your payload with the block size. An example of the latter would be to send the block size as the block header (say, an int in network byte order) so that the receiving end could read the size first and then perform a loop that continuously reads from the socket until it reads exactly the required amount.
    In other words, TCP sockets just provide you with a continuous stream paradigm. You need to impose some kind of an application protocol on top of it to build client-server dialogs. This is what's done behind the scenes by CORBA, RMI, HTTP etc.
    If you need to read up on Berkely socket API specifically, Richard Stevens has written some excellent books.

  • DataOutputStream

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

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

  • DataInputStream.read()

    Hi
    Im using the DatainputStream class to read segments of a specified file.
    Im trying to acheive this by passing in the following parameters to the read method,
    myDataInputStream.read(myByteArray[], 512, 512)
    Where my file in the datainputstream has a length of 31,000 (there abouts).
    The byte[] has a length of 512.
    My problem lies in the fact that the API states
    "If off is negative, or len is negative, or off+len is greater than the length of the array b, then an IndexOutOfBoundsException is thrown. "
    I want to take 512 bytes of the file starting at the position of 512 (offset). However because offset (512) + length (512) > 512 (byte[] length) then I get a indexoutofboundexception. This seems odd because it contradicts the whole purpose of providing an offset.
    I must be missing something here. Any help would be appreiciated with this matter.
    Thanks in advance
    Mark

    The offset refers to the byte[]. If you want to read starting at byte index 512, do a skip(512) before.

  • DataInputStream: method readLine() is deprecated. (What's the alternative?)

    Hi there,
    I have a DataInputStream object (code below). The code works great but I get a warning message below the code: dis.readLine()
    The method readLine() from the type DataInputStream is deprecated
    does anyone have an alternative to eliminate the warning?
    DataInputStream dis = null;
    String line = null;
    //read
    File f = new File(inputFolder+"/"+inputFileName);
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    dis = new DataInputStream(bis); 
    while ( (line=dis.readLine()) != null )
    }

    http://java.sun.com/j2se/1.4.2/docs/api/java/io/DataInputStream.html
    readLine()
    Deprecated. This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
    DataInputStream d = new DataInputStream(in);
    with:
    BufferedReader d
    = new BufferedReader(new InputStreamReader(in));

  • Implementing C language TCP header using Java

    Hello,
    I am in need of implementing the following C language code under Java...
      short len;
      struct
        char trans_id[4];
        char trans_filler[46];
        char data_vector[2];
        char data_len[2];
      } tcp_hdr;
      len = 257;
      memcpy(&tcp_hdr.trans_id[0], "SURV", 4);
      memset(&tcp_hdr.trans_filler[0], NULL, sizeof(tcp_hdr.trans_filler);
      tcp_hdr.data_vector[0] = 0x00;
      tcp_hdr.data_vector[1] = 0x08;
      memcpy(&tcp.hdr.data_len[0], &len, 2);
    }The code is used to create a TCP header that is prefixed on all Socket messages sent to the host.
    I thought I would throw this out and see if anyone has any ideas on how to implement this...
    Thanks.
    -Jeff

    Hello,
    I am in need of implementing the following C language
    code under Java...
    short len;
    struct
    char trans_id[4];
    char trans_filler[46];
    char data_vector[2];
    char data_len[2];
    } tcp_hdr;
    len = 257;
    memcpy(&tcp_hdr.trans_id[0], "SURV", 4);
    memset(&tcp_hdr.trans_filler[0], NULL,
    sizeof(tcp_hdr.trans_filler);
    tcp_hdr.data_vector[0] = 0x00;
    tcp_hdr.data_vector[1] = 0x08;
    memcpy(&tcp.hdr.data_len[0], &len, 2);The code is used to create a TCP header that is
    prefixed on all Socket messages sent to the host.
    I thought I would throw this out and see if anyone
    has any ideas on how to implement this...
    Thanks.
    -JeffWhat is the problem? You can write an identical header in many different ways. One is to use DataOutputStream.
    Kaj

Maybe you are looking for