Writing to an InputStream

I've encountered a rather unusual problem where I actually have to write directly from a program to an InputStream... I have tried using a PipedInputStream and hooking it up with a PipedOutputStream but whenever I try to do that it seems to deadlock my thread and kill my program. Does anyone have any suggestions about how I could do this? Code would be helpful but not necessary.
GN

Ok, thanks... That probably would have solved my
problem, but I ended up just extending InputStream, it
proved to be easier than multi-threading.Can you tell me how you solved this problem, 'coz I ran into the same situation right now and I need to solve it fast.
Thanks in advance,
--kiran                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Writing InputStream in Request to OutputStream in Servlet

    Hello folks,
    I've implemented a servlet that i use for uploading files to a server. The file to upload can be received as an InputStream in the Request body. I'm writing the the InputStream to an OutputStream. I had this problem, that it didn't work with large files with a size greater than 500kb (approximately). The servlet was called more than once for large files and the written file had a size of approximately 128kb on the server. My code was:
            final ServletInputStream in = req.getInputStream();
            final OutputStream out = new FileOutputStream( file );
            try
              final byte[] buf = new byte[1024];
              int len = 0;
              while ( ( len = in.read( buf ) ) != -1 )
                out.write( buf, 0, len );
                buf = new byte[buf.length << 1];
            finally
              in.close();
              out.close();
            }For performance reasons, i increased the size of the buffer with every turn (buf = new byte[buf.length << 1];). This is, why it couldn't save large files! When i do not increase the size of the buffer, everything works fine.
    My question is now: Why doesn't the code work with increasing the buffer?
    Thanks in advance,
    Robert

    How did you compile that code? And why are you bitshifting the buf.length?
    Well, get through a basic Java I/O tutorial and read on how to write an InputStream to an OutputStream. I personally suggest you to drop that byte block and use BufferedInputStream and BufferedOutputStream.
    http://www.google.com/search?q=java+io+tutorial+site:sun.com

  • Writing InputStream object to a file.

    I want to write a InputStream object to a file. How can this be done?
    Help please

    Fucking spammer.
    http://forum.java.sun.com/thread.jspa?threadID=612286&messageID=3377965#3377965

  • Runtime.exec("Perl Script writing and reading on I/O"), handling Streams

    Hi all !!
    In a first place : sorry for my english if it's not really understandable but I try to do as good as possible !
    I'm writing a GUI with Swing that will allow (in one of my multiple tables) the user to run a Perl Script.
    This Perl Script ask the user to choose a Folder ... then read all the files in this folder and for each file (xml File), extract the datas and put them in a database. But when a file that has to be inserted in the database contains this line : <Template_Used name="ST1.mtt"> and if the Template table in my database doesn't have the "ST1.mtt" stored ... the Perl Script ask to the user to give him the path of the file "ST1.mtt" so that the script can put the "ST1.mtt template" datas in the database.
    This script runs well when it is from a windows console.
    But I need a graphic interface !!!
    So I created a JButton "Process a folder".
    When the button is pressed, a JFileChooser appears and ask the user which Folder has to be processed.
    Then a Process is created with the command : ("cmd.exe /C \"C:\\Program Files\\Fluke\\Ansur\\ProcessFolder.bat\").
    The BatFile :
    {code}cd C:\Documents and Settings\tsd\Desktop\Gael-Project\Project_Files
    perl Process.pl
    exit{code}
    At this moment everything is working well.
    But my Process.pl (which is 300 lines long ... and that you don't even want to hear about), ask in a first time the Path of the folder to process and sometimes ask the path to a file (a template file).
    So I need to read and wirte on the STDIN/STDOUT during the exec of the Process.
    In order to handle this I created two different threads : one reading the Process.getInputStream with a BufferedReader and one other writing on the Process.getOutputStream with a PrintWrinter.
    What I need to do is :
    When I read a line from the InputStream saying "I need the path of the ST1.mtt file", I should run a JFileChooser ... the user find the file in the computer ... and I write in the OutputStream the path of the file, so that my Perl Script doesn't have un Unitialised value on <STDIN> and can continue to process !!
    I'm pretty sure it's possible ... because at the moment I just used a trick :
    When the user push the "process a folder" button, I write the paths in the OutputStream before than the script needs it and it works !
    But I need to write in the OutputStream only when it is time !!!
    Any idea ??
    Here are some parts of my code :
    {code}
    String filename = File.separator+"tmp";
              JFileChooser fc = new JFileChooser(new File(filename));
              fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY );
              // Show open dialog; this method does not return until the dialog is closed
         fc.showOpenDialog(null);
         Folder = fc.getSelectedFile();
              new GoodExec(cmd);
    {code}
    {code}
    public class GoodExec {
         public static Process proc;
         public static StreamGobbler errorGobbler;
         public static StreamGobbler inputGobbler;
         public static StreamGobbler outputGobbler;
         public GoodExec(String cmd)
         try
                   Runtime rt = Runtime.getRuntime();
              proc = rt.exec(cmd);
         // any error message?
         errorGobbler = new
         StreamGobbler(proc.getErrorStream(), "ERROR");
         // any input?
         inputGobbler = new
         StreamGobbler(proc.getInputStream(), "INPUT");
         // any output?
              outputGobbler = new
              StreamGobbler(proc.getOutputStream(), "OUTPUT");
         // kick them off
         errorGobbler.start();
         inputGobbler.start();
         outputGobbler.start();
         // any error???
         int exitVal = proc.waitFor();
         System.out.println("ExitValue: " + exitVal);
         } catch (Throwable t)
         t.printStackTrace();
    {code}
    {code}
    public class StreamGobbler implements Runnable
    InputStream is;
    OutputStream os;
    String type;
    Thread thread;
    public static String chaine;
    StreamGobbler(InputStream is, String type)
    this.is = is;
    this.os=null;
    this.type = type;
    StreamGobbler(OutputStream os, String type)
    this.os = os;
    this.is=null;
    this.type = type;
    public void start () {
         thread = new Thread(this);
         thread.start ();
    public void run()
    try
    if (is == null){
         PrintWriter toProgram = new PrintWriter(os);
         File FolderToProcess = ProcessFolder.Folder;
    String Folder = FolderToProcess.getPath();
    toProgram.write(Folder);
    toProgram.close();
    else {
         if (os == null){
         InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line=null;
    String comp = "Please enter the exact path of the directory that contains the files you want to process.";
    while ( (line = br.readLine()) != null){
         if (type.equals("INPUT")){
              chaine+=line+"\n";
         if (line.equals(comp)) {
              System.out.println("give directory");RUN A JFILECHOOSER AND GIVE THE DIRECTORY TO THE OUTPUTSTREAM
    System.out.println(type + ">" + line);
    is.close ();
    catch (IOException ioe){
         ioe.printStackTrace();
    {code}
    And here is an example of a simple perl script that could be used (it s a simple one !!) :
    {code}
    #!/usr/bin/perl -w
    use strict;
    print "Please enter the exact path of the directory that contains the files you want to process.\n";
    my $dir= <STDIN>;
    chomp ($dir);
    print "titallala $dir";
    if (the template of the file is not in the database){
    print "Please give me the template so that I can put it in the database";
    $dir= <STDIN>;
    chomp ($dir);
    {code}
    Thank you for your help ... if it's possible to help me !!
    Gael

    BalusC -- The line that gives me my NullPointerException is when I call the "DisplayProduct()" method. Its a dumb question, but with NetBeans how do I find out which reference could be null? I'm not very familiar with how NetBeans works with finding out how to debug. Any help you can give me would be greatly appreciated.The IDE is com-plete-ly irrelevant. It's all about the source code.
    Do you understand anyway when and why a NullPointerException is been thrown? It is a subclass of RuntimeException and those kind of exceptions are very trival and generally indicate an design/logic/thinking fault in your code.
    SomeObject someObject = null; // The someObject reference is null.
    someObject.doSomething(); // Invoking a reference which is null would throw NPE.

  • How to transfer the content in a StringBuffer into a InputStream

    I need append the comment to the buttom of each file. I read the file into the stringbuffer first, appending the comments. After completed, how can I send the content in the StringBuffer back into a InputString in order to continue with some other file manipulation?
    I saw a method StringBuffer.toString(), but nothing to transfer back to InputString
    Thank you in advance

    How aboutnew StringReader(sb.toString());Since you are working with text data, you should be working with Readers instead of InputStreams.
    (And if you are appending data to a file, wouldn't it be more effective to just use the version of FileWriter that allows you to append the data, instead of reading the whole file and writing the updated file back?)

  • How to create a MimeBodyPart properly with an InputStream in the constructo

    I am looping through a list of email attachments.
    In this loop I am doing the following:
    (Don't worry about the Core object, it works and returns a valid InputStream, tested this before by just reading out the bytes)
                     InputStream attachInputStream = Core.getFileDocumentContent(attachObject);
                       System.out.println("available for original stream: " + attachInputStream.available());
                       MimeBodyPart attachmentBodyPart = new MimeBodyPart(attachInputStream);
                       InputStream testStream = attachmentBodyPart.getInputStream();
                       System.out.println("available for retrieved stream: " + testStream.available());
                       attachmentBodyPart.setFileName(attachment.getName());
                   multipart.addBodyPart(attachmentBodyPart);Because my received attachments were always empty, I added a few println's to check where this were going wrong. Following is the output when I run the application:
    available for original stream: 119
    available for retrieved stream: 0
    So, apparently something goes wrong in the constructor for MimeBodyPart.
    I hope I'm just doing something silly but I'm out of options at the moment apart of writing a lot of extra code to handle converting an InputStream to a MimeBodypart myself.
    Anyone with some ideas?
    edit: I just read I cannot use available after getting an inputstream from a mimebodypart. So I'll go and make another check. Problem still exists though, I'm not getting an attachment after mailing it.
    Edited by: Bas_Rotterdam on Apr 15, 2009 3:16 AM

    I'm not clear on what you're trying to accomplish.
    Are you trying to create a message with attachments, where the content of the
    attachments comes from InputStreams from your Core object? If so, you're
    going about it the wrong way.
    The MimeBodyPart constructor expects the input stream to be formatted as
    an entire body part - headers plus content. You only have the content. For
    that you want to use the setContent method or one of the related methods
    (setDataHandler, setText, attachFile) that sets the content of the body part.
    See the sendfile.java demo program included with JavaMail for an example of
    creating an attachment with content from a file.
    And don't forget to read the [JavaMail FAQ|http://java.sun.com/products/javamail/FAQ.html].

  • Writing to file

    public static void main(String args[]) throws Exception
    String str1;
    int length;
    BufferedReader inpu=new BufferedReader(new InputStreamReader(System.in));;
    System.out.println("Enter something: ");
    str1=inpu.readLine();
    System.out.println("hai"+" "+str1);
    i ve used the above code to read an input from the user now i want to write this to a file.plz tell me how to do it

    ya i tried using FileWriter
    But is there any other methods
    import java.io.*;
    class readtofile
    public static void main(String args[]) throws Exception
    String str1;
    int length;
    //stream given to inputstream reader then buffered usin buffered reader
    BufferedReader inpu=new BufferedReader(new InputStreamReader(System.in));;
    System.out.println("Enter something: ");
    str1=inpu.readLine();
    System.out.println("hai"+" "+str1);
    //opening a new file for output
    File outfile_1= new File("testout.txt");
    //using filewriter class for writing to file
    FileWriter out= new FileWriter(outfile_1);
    out.write(str1);
    out.close();
    }

  • InputStream / OutputStream Help

    I have in a series 10 commands to be executed on a server. so i am using Buffered OutputStream and DataOutputStream to write those commands to server.
    these commands have a set of protocol rule to be followed.
    for example i am creating a byte array and i am appending those protocol rules to the byte array and then finally to the stream and then writing to the socket of the server.
    everything works fine here.
    After that i must read the messages from the server.
    this is also fine but t�he problem is everytime i read different input for each command.
    i dont know why!!!!
    so my read function is as follows,
    import java.net.*;
    public class xxxxx
    InputStream instream;
    OutputStream outstream;
    public void OpenConnection() throws ConnectException,UnknownHostException
    try
         tcpipSocket = new Socket(tcpipparameters.getIpAddress(),tcpipparameters.getPortNumber());
    catch(IOException exception)
         System.out.println(exception.toString());
    try
         outstream = tcpipSocket.getOutputStream();
         instream = tcpipSocket.getInputStream();
         dos = new DataOutputStream(outstream);
         BufferedOutputStream bos= new BufferedOutputStream(dos);
         dis = new DataInputStream(instream);
         BufferedInputStream bis = new BufferedInputStream(dis);
    ////////// now i start the command execution on the server
    ///// The 1st Command --------------(The INIT Command)
         byte[] init = {0,6,0,2};
         init = createMessage.calculateCheckSum(init);
         int len = init.length;
         //dos.write(init,0,len);
         bos.write(init);
         bos.flush();
         int available;
         while((available = bis.available()) > 0)
              byte[] data = new byte[available];
              bis.read(data);
              for(int i = 0 ; i < data.length; i++)
                   System.out.print(data);
    ////////////////// The 2nd Command -------------------(IDENTIFY)
    byte[] identify = {0,16,0,20};
    // The protocol version number is inserted in to the IDENTIFY byte[]array
    int protocol_version_number = 512;
    byte[] protocol = {(byte)(protocol_version_number/256) ,(byte)(protocol_version_number%256) };
    byte[] temp = new byte[ identify.length +  protocol.length] ;
    System.arraycopy( identify, 0, temp, 0, identify.length ) ;
    System.arraycopy(protocol, 0, temp, identify.length, protocol.length ) ;
    identify = temp ;
    String PR_SName = "PRS2.0";
    identify = createString.stringData(identify,PR_SName);
    identify = createMessage.calculateCheckSum(identify);
    len = identify.length;
    bos.write(identify);
    bos.flush();
    int length1 = bis.available();
    System.out.println("length of the BufferedInputStream = " + length1);
    StringBuffer sb = new StringBuffer();
    for (int i=1; i<=length1; i++)
         char reply = (char)bis.read();
         sb.append(reply);
    System.out.println(sb.toString());
    ////////////////// The 3rd Command and So on................................
    catch(IOException exception)
         System.err.println("message = " + exception.getMessage());
    catch(InterruptedException e)
         System.err.println("Error =" + e);
    finally
         try
              //flush and close both "Instream" and "Outstream"
              dos.close();
              dis.close();
              instream.close();
              outstream.close();
         catch (IOException ex)
              ex.printStackTrace();
    every time the reading from the server is different.
    but i want to have the exact number of bytes to read everytime.
    so please correct me where i am wrong.
    With regards,
    Ashok
              public void CloseConnection()throws IOException
                        tcpipSocket.close();

    I would say the answer is in my previous replies to your question. I suggest you have another read of them.

  • Writing a Vector to a Output File Line by Line.

    Can anyone tell me how to write each element of the Vector on a New Line to the Output file? Right now the Output is in a String across 1 line.
    Now - � t Bowser 5 years 105 lbs.t Bowser 5 years 106 lbs.t Daisy 1 year 30 lbs.t Dog 1 yr 66 lbs.t King 6 years 77 lbs.t Nikki 5 years 68 lbs.
    Here is what I need -
    Bowser 5 years 106 lbs.
    Bowser 5 years 105 lbs.
    Rover 7 years 88 lbs.
    Dog 1 yr 66 lbs.
    King 6 years 77 lbs.
    Nikki 5 years 68 lbs.
    Daisy 1 year 30 lbs.
    Do a find on // Writes Vector Object to a file
    Thank You in advance.
    import java.io.*;
    import java.awt.*;
    import java.util.*;
    public class VectorSort
    Vector v;
    private DataInputStream inputStream = null;
    private ObjectOutputStream outputStream = null; // <== this is for a Vector
    // private DataOutputStream outputStream = null; // <== This is for a Textfile
    (1) Read in Pet Records put them in a Vector, Sort them Print them.
    public static void main(String[] args) throws java.io.IOException
    VectorSort newVector = new VectorSort();
    newVector.connectToInputFile();
    newVector.connectToOutputFile();
    newVector.readInput();
    newVector.sortPrint();
    newVector.closeFiles();
    System.out.println(" ");
    System.out.println("Check A:/DataOut.txt Now");
    public void connectToInputFile()
    String inputFileName = getFileName("Enter input file name: A://DataIn.txt");
    try
    inputStream = new DataInputStream(new FileInputStream(inputFileName));
    catch(FileNotFoundException e)
    System.out.println("File " + inputFileName + " not found.");
    System.exit(0);
    public void connectToOutputFile()
    String outputFileName = getFileName("Enter output file name: A://DataOut.txt");
    try
    outputStream = new ObjectOutputStream( // <== this is for a Vector
    // outputStream = new DataOutputStream( // <== this is for a Textfile
    new FileOutputStream(outputFileName));
    catch(IOException e)
    System.out.println("Error opening output file "
    + outputFileName);
    System.out.println(e.getMessage());
    System.exit(0);
    private String getFileName(String prompt)
    String fileName = null;
    System.out.println(prompt);
    fileName = SavitchIn.readLineWord();
    return fileName;
    //===========================================================================
    public void readInput()
    v = new Vector ();
    try
    String result = "";
    boolean done = false;
    int ctr = 0;
    String next;
    next = inputStream.readLine();
    while ( next != null)
    v.addElement( next.trim() );
    next = inputStream.readLine();
    catch(EOFException e)
    //Do nothing. This just ends the loop.
    System.out.println("Do Nothing Here");
    catch(IOException e)
    System.out.println(
    "Error: reading or writing files.");
    System.out.println(e.getMessage());
    System.exit(0);
    public void sortPrint()
    Collections.sort(v);
    int vsize = v.size();
    for (int j = 0; j < vsize - 1 ; j++)
    try
    outputStream.writeObject(v.elementAt(j)); // Writes Vector Object to a file
    System.out.println(v.elementAt(j));
    catch(IOException e)
    System.out.println("Error Writing Output "
    + e.getMessage());
    System.exit(0);
    public void closeFiles()
    try
    outputStream.flush(); // <== force the buffer to write
    inputStream.close();
    outputStream.close();
    catch(IOException e)
    System.out.println("Error closing files "
    + e.getMessage());
    System.exit(0);

    // did you try with java.io.PrintWriter
    // here is simple method to write file from vector.
    // you need to change obtaining your string value at the vector loop
    private void writeDataLog(Vector vector, String filename)
    try
    PrintWriter pw = new PrintWriter(new FileWriter(filename, true));     
    if (vector.size()>0)
    for (int i=0; i<vector.size(); i++)
    { String str = ((your object)vector.get(i)).getYourString();
    pw.println( str );
    pw.close();
    catch(Exception e)
    { System.out.print(e.toString()); }
    }

  • Error while writing to a file

    Hi,
    I am getting an error while writing to a file.Here is the sample code in which I am getting error.The STDERR is getting printed to console but the same is not getting written to a file.
    package Sample;
    import java.util.*;
    import java.io.*;
    public class MediocreExecJavac
    public static void main(String args[])
    try
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("perl ic_start");
    InputStream stderr = proc.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr);
    BufferedReader br = new BufferedReader(isr);
    FileWriter fw=new FileWriter("result.txt");
    String line = null;
    System.out.println("<ERROR>");
    while ( (line = br.readLine()) != null)
    System.out.println(line);
    fw.write(line);
    System.out.println("</ERROR>");
    int exitVal = proc.waitFor();
    System.out.println("Process exitValue: " + exitVal);
    fw.close();
    } catch (Throwable t)
    t.printStackTrace();
    }Below is the output -
    <ERROR>
    Can't open perl script "ic_start": No such file or directory
    java.lang.NullPointerException
    at java.io.Writer.write(Unknown Source)
    at Sample.MediocreExecJavac.main(MediocreExecJavac.java:21)
    Please tell where the program is going wrong.

    i think it is just the path of file that u r missing

  • Java.io.StreamCorruptedException: InputStream does not contain a serialized object

              I have an applet which calls a JSP to write data object to the db and then the
              JSP sends back the updated data object. The writing part is ok but the response
              is giving the following error. The data object is in a separate class which implements
              Serialized.
              Here's the code in the applet calling the JSP and the response from the JSP
              URL server = null;
              String urlConnectionString = "http://localhost:7001/isLoginValid.jsp";
              try
              server = new URL(urlConnectionString);
              catch(MalformedURLException e)
              System.out.println("URL exception: " + e );
              // send request
              ObjectInputStream response = null;
              Object result = null;
              try
              URLConnection conn = server.openConnection();
              conn.setDoOutput(true);
              conn.setUseCaches(false);
              conn.setRequestProperty("Content-Type", "application/octet-stream");
              ObjectOutputStream request = new ObjectOutputStream(new
              BufferedOutputStream(conn.getOutputStream()));
              request.writeObject((Object)dvo);
              request.flush();
              request.close();
              // get the result input stream
              response = new ObjectInputStream(new BufferedInputStream
              (conn.getInputStream()));
              // read response back from the server
              result = response.readObject();
              if( result!=null && (result instanceof DataVO))
              dvo = (DataVO)result;
              String vo = dvo.printDataVO();
              System.out.println("*DataVO*\n"+vo);
              else
              System.out.println("not an instanceof DataVO");
              catch(IOException ignored)
              System.out.println("Error in DataVO response");
              ignored.printStackTrace();
              Here's the code in the JSP sending the response back to the applet. The 'dvo'
              object is the object which is serialized and has gets and sets for the diff. data
              elements. When I print the 'dvo' before writing the object to outputStream it
              prints the correct values for the data element.
              // send response
              response.setStatus(HttpServletResponse.SC_OK);
              ObjectOutputStream outputStream = new ObjectOutputStream (new BufferedOutputStream
              (response.getOutputStream()));
              outputStream.writeObject(dvo);
              outputStream.flush();
              ERROR is as follows:
              Error in DataVO response
              java.io.StreamCorruptedException: InputStream does not contain a serialized object
              at java/io/ObjectInputStream.readStreamHeader
              at java/io/ObjectInputStream.<init>
              What am I doing wrong?. Please respond soon. The applet is run on IIS and the
              JSP in on weblogic 6.1. I'm not sure if that makes any difference.
              

              I have an applet which calls a JSP to write data object to the db and then the
              JSP sends back the updated data object. The writing part is ok but the response
              is giving the following error. The data object is in a separate class which implements
              Serialized.
              Here's the code in the applet calling the JSP and the response from the JSP
              URL server = null;
              String urlConnectionString = "http://localhost:7001/isLoginValid.jsp";
              try
              server = new URL(urlConnectionString);
              catch(MalformedURLException e)
              System.out.println("URL exception: " + e );
              // send request
              ObjectInputStream response = null;
              Object result = null;
              try
              URLConnection conn = server.openConnection();
              conn.setDoOutput(true);
              conn.setUseCaches(false);
              conn.setRequestProperty("Content-Type", "application/octet-stream");
              ObjectOutputStream request = new ObjectOutputStream(new
              BufferedOutputStream(conn.getOutputStream()));
              request.writeObject((Object)dvo);
              request.flush();
              request.close();
              // get the result input stream
              response = new ObjectInputStream(new BufferedInputStream
              (conn.getInputStream()));
              // read response back from the server
              result = response.readObject();
              if( result!=null && (result instanceof DataVO))
              dvo = (DataVO)result;
              String vo = dvo.printDataVO();
              System.out.println("*DataVO*\n"+vo);
              else
              System.out.println("not an instanceof DataVO");
              catch(IOException ignored)
              System.out.println("Error in DataVO response");
              ignored.printStackTrace();
              Here's the code in the JSP sending the response back to the applet. The 'dvo'
              object is the object which is serialized and has gets and sets for the diff. data
              elements. When I print the 'dvo' before writing the object to outputStream it
              prints the correct values for the data element.
              // send response
              response.setStatus(HttpServletResponse.SC_OK);
              ObjectOutputStream outputStream = new ObjectOutputStream (new BufferedOutputStream
              (response.getOutputStream()));
              outputStream.writeObject(dvo);
              outputStream.flush();
              ERROR is as follows:
              Error in DataVO response
              java.io.StreamCorruptedException: InputStream does not contain a serialized object
              at java/io/ObjectInputStream.readStreamHeader
              at java/io/ObjectInputStream.<init>
              What am I doing wrong?. Please respond soon. The applet is run on IIS and the
              JSP in on weblogic 6.1. I'm not sure if that makes any difference.
              

  • InputStream from a String?

    Hi all,
    does anybody know how you would go about getting a java.io.InputStream from a string object? I know you can create a StringReader from a string, but the StringBufferInputStream is depreciated. I want to parse an xml String with the DocumentBuilder class, but it only takes an InputStream object, not a Reader object.
    any suggestions?
    thanks,
    J

    Adding to Mr. Sampieri's explanation:
    The encoding is specified in the initial processing instruction of the XML. If absent, the default encoding is UTF-8. (The default encoding of Java depends on the locale, so it's better to specify the correct encoding when writing your program.)
    Check if the names of the XML encodings are different from the names of the Java encodings (charsets).
      <?xml version="1.0" encoding="ISO8859-1" ?>

  • Parse method of JAXP DocumentBuilder using InputStream

    I am having some problem. I am working on a generic XML messaging client server pair. The crux of it is that I am using the Transformer object to send data from the client to the server, using a Socket InputStream. The I do exactly the same from the server side to the client side.
    Example (client side):
    OutputStream out = socket.getOutputStream();
    Transformer transformer =
    TransformerFactory.newInstance().newTransformer();
    transformer.transform(new DOMSource(request),
    new StreamResult(out));
    Example (server side, in the thread for the connection):
    InputStream in = socket.getInputStream();
    DocumentBuilder builder =
    DocumentBuilderFactory.newInstance
    ().newDocumentBuilder();
    Document request = builder.parse(in);
    The problem I am experiencing is that the parse method on the server side is never completing. The parse method does not return at all. I can understand that this is due to the InputStream still being open, and need to know how can I let the parse method know that I am done writing to the OutputStream at the client side. Should I be sending an EOF character of sorts? If I should, what byte value represents this, and what do I need to do?
    Thank you
    Heinrich Pool

    Sorry hadn't noticed the Code Tags before. So the code formatted
    package de.gaskin.xml;
    import de.gaskin.buf.Buffer;
    import de.gaskin.io.LineArray;
    import de.gaskin.util.Debug;
    import java.net.Socket;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.io.ByteArrayOutputStream;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.util.Vector;
    import org.w3c.dom.Document;
    A Simple to use generic XML Document transfer based on sockets.
    <H2>Theory of Operation.</h2>
    <p>A client sends an array of lines (an XML document) prepended by a line
    that ONLY contains an integer (the number of lines in the document that
    follows).
    <p>The server reads the first line (so that it knows how many lines belong to
    the next document) it then reads the specified number of lines into memory and
    when all lines have been read in passes them (as an InputStream) to an
    XMLParser to produce an XML DOM that is made available through the<br>
    <code>getDocument()</code> method.
    <h2>API</h2>
    The API is very simple to use as the following templates demonstrate.
    <h3>Client</h3>
    <pre>
        public class MyXmlSocketClient extends XmlSocket {
           MyXmlSocketClient(String serverAddress, String fileName) {
              super(serverAddress, 4711);
              run(fileName);
    </pre>
    <h3>Server Worker</h3>
        <pre>
        public class MyXmlSocketServer extends XmlSocket {
           MyXmlSocketServer(Socket s) {
              super(s);
           public void run() {
              Document doc = getDocument();
              // Process document
        </pre>
    <h3>Server Listener</h3>
        <pre>
        public class MyXmlServer {
           ServerSocket ss;
           boolean      stop;
           MyXmlSocketServer() {
              stop = false;
              try {
                 ss = new ServerSocket(4711);
                 while (! stop) {
                    Socket s = ss.accept();
                    new Thread(new MyXmlServerSocket(s));
              catch (Exception x) {
                 x.printStackTrace();
        </pre>
    <P>Last updated 10th Jan 2001.
    @author  David. M. Gaskin.
    @version Version 1.0 Oct 2000
    @since    Version 1.0
    public class XmlSocket implements Runnable {
       final static boolean debug = false;
       protected BufferedReader  data;
      /* protected */ public PrintWriter     pw;
                 Socket          socket;
       public XmlSocket(String domain, int port) {
          try {
             socket = new Socket(domain, port);
             common(socket);
          catch (Exception x) {
    //       x.printStackTrace();
             throw new Error(x.toString());
       public XmlSocket(Socket s) {
          socket = s;
          common(s);
       void common(Socket s) {
          try {
             data = new BufferedReader(new InputStreamReader(s.getInputStream()));
             pw   = new PrintWriter(s.getOutputStream(), true);
          catch (Exception x) {
    //       x.printStackTrace();
             throw new Error(x.toString());
       public Document getDocument() {
          Document rc = null;
          try {
             String line = data.readLine();
             int    linesInDoc = Integer.parseInt(line.trim());
             if (linesInDoc != -1) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                for (int i = 0;i < linesInDoc;i++) {
                   line = data.readLine();
                   System.out.println(line);
                   byte[] byteLine = line.getBytes();
                   os.write(byteLine, 0, byteLine.length);
    //          System.out.println("END");
                rc = XmlFactory.readIn(new ByteArrayInputStream(os.toByteArray()));
          catch (Exception x) {
             x.printStackTrace();
          return rc;
       public void run(Vector lines) {
          int loopCnt = lines.size();
          if (debug) {
             println("" + loopCnt);
             for (int i = 0;i < loopCnt;i++) {
                println((String)lines.elementAt(i));
    //       pw.flush();
             println("-1");
          else {
             pw.println("" + loopCnt);
             for (int i = 0;i < loopCnt;i++) {
                pw.println((String)lines.elementAt(i));
    //       pw.flush();
             pw.println("-1");
          pw.flush();
       void println(String s) {
          System.out.println(s);
          pw.println(s);
       public void run() {
          Debug.d(this, "run", "S H O U L D   N E V E R   B E   I N V O K E D");
       public void run(String filename) {
          Buffer[] input = LineArray.readIn(filename);
          send(input);
       public void run(File file) {
          Buffer[] input = LineArray.readIn(file.getAbsolutePath());
          send(input);
       void send(Buffer[] input) {
          int loopCnt = input.length;
          pw.println("" + loopCnt);
          for (int i = 0;i < loopCnt;i++) {
             pw.println(input.toString());
    pw.flush();
    pw.println("-1");
    pw.flush();
    public int getDocIdx(String[] roots, Document doc) {
    int rc = -1;
    String rootName = doc.getDocumentElement().getTagName();
    int loopCnt = roots.length;
    for (int i = 0;i < loopCnt;i++) {
    if (rootName.equals(roots[i])) {
    rc = i;
    break;
    if (rc < 0)
    System.out.println(rootName + " N O T F O U N D");
    return rc;
    public Socket getSocket() {
    return socket;
    For testing only
    public static void main(String[] args) {
    XmlSocket xmlS = new XmlSocket("localhost", 36);
    xmlS.getDocument();

  • Form on screen, not updating for new data on inputstream

    I'm writing a j2me midlet that will initiate a bluetooth connection to another device. I have been able to set up the inputstreams and outputstreams and send some data between the two devices using serial port emulation.
    The following is the code for this part of the program:
    ServiceRecord s = (ServiceRecord) serviceVector.elementAt(a);
            int data[] = new int[10000];
            InputStream in = null;
            OutputStream out = null;
            Form dataForm = new Form("Data");
            dataForm.addCommand(exitCommand);
            dataForm.addCommand(backCommand);
            dataForm.setCommandListener(this);
            display.setCurrent(dataForm);
            try {
                StreamConnection conn = null;
                String url = null;
                try {
                    url = s.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
                    conn = (StreamConnection) Connector.open(url);
                } catch (IOException e) {
                    System.err.println("Note: can't connect to: " + url);
                in = conn.openDataInputStream();
                out = conn.openDataOutputStream();
                int ch;
                out.flush();
                    while (((ch) = in.read()) != -1) {
                        String aChar = new Character((char)ch).toString();
                        dataForm.append(aChar);
                        dataForm.append("\n");
                conn.close();My problem is that the midlet on the mobile phone will only update its window to display the new screen as a form once the connection has been terminated, that is when the while loop has been broken. Is there a way in which to display the form while the inputstream is waiting for data and then watch the addition of data in real time to the form?
    I am relatively new to java and have searched the forum/ internet for such a problem but have not been able to find a solution. Cheers

    I don't think that is it now that we are into Monday and it still hasn't updated. Anybody else having issues with their text descriptino not updating? What's a good email address to contact apple about the problem. Non of the "contact Us" email addresses seem to fit the description. The [email protected] is a blackhole.

  • Socket reading & writing - minimize latency

    Hello,
    I'm having a big application which reads & writes on a regular socket, and I'm trying to reduce latency to the minimum.
    to understand & measure things a bit better, I've written a simple client/server couple app: client connects to server, sends messages of specified length, server echoes messages back to client, that reads them.
    I'm running both client & server on the same box so that I have no timestamps issues.
    for this test, rate of sending messages is 1 every 400ms, size of message is 512 Bytes.
    I get average Round Trip Time of 560 micro-seconds, but variations are impressive, with values between 28 micro-second and 1.5milliseconds.
    I'd like to try to lower this latency to the minimum possible, and would like to hear what are the FASTEST & most Jitter-free ways of doing so, and I'm ready to experiment.
    on the client I do initially:
    _out = new DataOutputStream(_socket.getOutputStream()); then write regularly with
    String msg = "whatever_512_characters_msg";
    _out.writeBytes(msg);server side:
    _in = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
    _out = new PrintWriter(_socket.getOutputStream(), true);reading is done with _in.readLine()writing is done with _out.println(msg);even though things are working OK, I'm thinking there must be a faster way to do things...
    the goal is not to optimize throughput or bandwidth, but really latency for roughly 512 Bytes messages.
    any pointer would be appreciated...
    thanks

    - how do PrintWriter and BufferedOutputStream are supposed to compare ?Don't use a PrintWriter for network operations. It swallows exceptions that you need to know about. You can use a BufferedWriter, if the other end is going to use a Reader.
    - what would be the advantage of using a byteArray (have seen this in several places, but don't exactly know how to implement it)If the data is already in a byte[] array, just write it using OutputStream.write(), and read it at the other end using InputStream.read(byte[]). If you do this you need to loop when reading until you've assembled a complete message, whatever that means. In your case you may be better off sticking with readLine().
    - people mentionned NIO, how would that be useful in such case, knowing that I'm mostly going to handle single connections ?Don't bother. NIO is for thousands of connections, not one.

Maybe you are looking for

  • Mini dvi to hdmi problems - displaying my screen on my TV

    so I have an Toshiba LCD TV with an HDMI port and I'd like to be able to play videos from the internet on my TV. I have a Macbook with a mini-dvi port so I bought a mini-dvi to HDMI adapter from Amazon and an HDMI cable from Best Buy. I also have an

  • FIXED: 'disk could not be read or written to'

    I was getting this error nonstop with my shuffle. Here's how I got it to work. Plug in your iPod. Make sure iTunes is open so Windows will see it as a disk (set it to Disk Use) Go to Start > Run > Type in 'diskmgmt.msc' You will see your iPod disk, j

  • Help: Net.lib interface error

    Hi! I'm using the Palm Emulator to make a HTTP connection to my servlet. The same MIDlet works on my Palm, but when I run it on the emulator (in order to some screen captures), I get error mesg that says "Net.lib interface error: 0x0000120C", followe

  • Can't download doc on MacBook that was uploaded from my iMac. How can?

    1. I create a Pages document on my iMac 2. Upload it to iCloud 3. Cannot download on my MacBook. 4  Only after I have opened it on my iPad it can be downloaded on my iMac and MacBook again. How Can ?

  • Playing multiple sounds at once

    Hi guys, I have this problem for some time now (I just havent got time to deal with it) - after latest installation of arch I am unable to play sound from multiple programs at once (eg from firefox and xmms). I tried to figure out alsa configuration