FileWriter to write bytes

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

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

Similar Messages

  • Static final buffer passed into FilterOutputStream.write(byte[])

    Greetings,
    My team is using a custom subclass of FilterOutputStream to XOR some bytes with a key before writing them to an underlying OutputStream. We have never had problems with it until we started testing with Java 1.4.x -- where we noticed that some optimizations had been made to GZIPOutputStream to write the GZIP header out at once using a static final buffer to hold the header.
    The problem seems to be that this header, although marked as static final, can still be changed when it is passed to our custom FilterOutputStream's write(byte[] b) method. For speed, we are XORing the bytes in place in the byte[] and then writing it directly back out. So every time we write the header with the same key, the static final byte[] that holds the header in GZIPOutputStream changes from its XORed to cleartext equivalent, and back.
    My question is this: should this be considered a bug in the SDK, or a bug in our code? Maybe I'm looking in the wrong place, but I can't find any documentation that specifies what can and can't be done with a byte[] that is passed into the write(byte[]) method of an OutputStream.
    Any input is appreciated.
    Regards,
    Mike Pontillo

    Mike,
    Need some code here to clarify. Are you saying that
    the original final static (constant) changes?
    You've got to be careful when you talk about passing a
    byte[], which can't be done, of course. You are
    passing a reference to a byte[]. Using the reference,
    the bytes can be copied. There aren't any restrictions
    on what can be done to the copy.
    and also, if you have final array, then only that arrays'
    reference is final, but the content of array may change
    as well as when that array wasn't static.Yes, I understand this. Thank you for your replies. FilterOutputStream.write(byte[]) of course takes a reference to a byte[]. We are overloading this to be something like:
    public void write(byte[] b) {
       for(int i = 0 ; i < b.length ; i++) {
          b[i] = foo(b);
    out.write(b);
    i.e. we modify the array inside the method rather than making a copy and writing out the copy.
    This hasn't been a problem until Java 1.4.x -- now GZIPOutputStream passes a private static final byte[] (reference of course) into write(byte[]) in OutputStream. So when our overloaded write(byte[]) method gets called in FilterOutputStream and code similar to the above runs, the private static final reference to a byte[] is overwritten in the java.util.zip.GZIPOutputStream class. This was a change sometime between 1.3 and 1.4, I believe. From the J2SDK 1.4.1_02 source:
         * Writes GZIP member header.
        private final static byte[] header = {
            (byte) GZIP_MAGIC,                // Magic number (short)
            (byte)(GZIP_MAGIC >> 8),          // Magic number (short)
            Deflater.DEFLATED,                // Compression method (CM)
            0,                                // Flags (FLG)
            0,                                // Modification time MTIME (int)
            0,                                // Modification time MTIME (int)
            0,                                // Modification time MTIME (int)
            0,                                // Modification time MTIME (int)
            0,                                // Extra flags (XFLG)
            0                                 // Operating system (OS)
        private void writeHeader() throws IOException {
            out.write(header);
        }As you can see, they are passing a private static final reference to a byte array into somebody's untrusted method (ours). =)
    Due to this issue we have to change our code so that it makes a copy of these bytes rather than changing them in the method. Now I'm wondering if this should be considered a bug in Java or not -- does changing bytes like this violate the general contract of an Input/Output stream? It at least seems like a bad idea for encapsulation purposes since anyone can change these bytes in the GZIPOutputStream class. We had previously assumed that if they were writing these bytes to an output stream they didn't care about them any more, which is the case 99.9% of the time in our experience.

  • Read/write bytes in unicode

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

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

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

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

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

  • About RandomAccessFile/Write byte

    Do you know the result and why ??
    public static void main(String[] args) throws IOException{
    RandomAccessFile raf = new RandomAccessFile("test.dat","rw");
    raf.writeInt(0x01);
    raf.writeShort(0x23);
    raf.writeByte(0x45);
    raf.seek(3);
    short a1 = raf.readShort();
    short a2 = raf.readShort();
    System.out.println("0x"+Integer.toHexString(a1)+", 0x"+Integer.toHexString(a2));

    The bytes are written as 0 0 0 1 0 35 69in the "test.data" file. Because you set the file pointer at the index 3 through seek(3), the bytes to be read are
    1 0 35 69and if byte array {1,0} is read as a Short object it becomes 0x100, and the remaining byte array {35, 69} as a Short object is 0x2345.

  • How to  write the bytes out

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

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

  • Writting to Bytes

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

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

  • Java in writting a byte

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

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

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

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

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

  • Character vs. Byte

    Hello ppl,
    I will appreciate if someone helps me fix this bugging problem. I have code that has created a text file using DataOutputStream dos = new DataOutputStream(new FileOutputStream(new File("file.txt"), true));
    dos.writeChars(str.toString());Now my problem is whenever I open text file created like above in editors like 'vi', 'emacs' etc., they show up as binary (which is expected since I used DataOutputStream to write bytes).
    My questions is this:
    I want to write another small piece of code that reads this text file and writes them back as plain characters and not binary data. I tried using
    DataInputStream dis = new DataInputStream(new FileInputStream(new File("file.txt")));
    PrintWriter pwriter = new PrintWriter(new FileWriter(new File("new-File.txt")));
    while(true)
         pwriter.print(dis.readChar());I also tried using BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("file.txt"))));and then using str = br.readLine();
    pwriter.print(str.toCharArray());I failed each time. Any suggestions on how to obtain text file with plain Ascii characters and not binary data.
    Thanks
    - Mitesh.

    Hi malcolm,
    I tried what you suggested. Its not working. All I got in the output file was characters like ????? Everything was a question mark. I tried different encodings. When I tried "UTF-8" I got the original file as output. The code I had used was exactly what you posted. Here is the code that I tried after several attempts of debugging and this works. It might be helpful to others:
    BufferedReader br = null;
    Writer out = null;
    char chr = ' ';
    int count = 0;
        try {
          br = new BufferedReader(new InputStreamReader(new FileInputStream("file.txt")));
          out = new FileWriter("fileConverted.txt");
          while(count != -1) { //this denotes end of file
            count = br.read();
            if (count == 0 || count == -1) // loop will break here if EOF detected
              break; // count = 0 indicates unused portion of Unicode character in the file.
            chr = (char)count; //else cast the ASCII value of int to char
            out.write(chr);
            count = br.read(); //Essentially we skip every alternate character in the input file.
    // The portion skipped is unused portion of Unicode character.
          br.close();
          out.close();
          System.out.println("Done");
        catch(EOFException ex) {
          ex.printStackTrace();
        catch(IOException ex) {
          ex.printStackTrace();
        catch(NullPointerException ex) {
          ex.printStackTrace();
    }

  • What is the proper way to use the write method?

    What is the proper way to use the OutputStreams write method? I know the flush() method is automatically called after the write but i cant seem to get any output
    to a file. The char array contains characters and upon completion of the for loop the contents of the array is printed out, so there is actually data in the array. But write dosnt seem to do squat no matter what i seem to do. Any suggestions?
    import java.io.*;
    public class X{
    public static void main(String[] args){
    try{      
    FileReader fis = new FileReader("C:\\Java\\Test.txt"); //read chars
    FileWriter fw = new FileWriter("C:\\Java\\Test1.txt"); //read chars
    File f = new File("C:\\Java\\Test.txt");
    char[] charsRead = new char[(int)f.length()];
    while(true){
    int i = fis.read(charsRead);
    if(i == -1) break;
    // fw.write(charsRead); this wont work
    // but there is infact chars in the char Array?
    for(int i = 0; i < charsRead.length -1 ; ++i){
    System.out.print(charRead);
    }catch(Exception e){System.err.println(e);}

    Sorry to have to tell you this guys but all of the above are broken.
    First of all... you should all take a good look at what the read() method actually does.
    http://java.sun.com/j2se/1.3/docs/api/java/io/InputStream.html#read(byte[], int, int)
    Pay special attension to this paragraph:
    Reads up to len[i] bytes of data from the input stream into an array of bytes. An attempt is made to read as many as len[i] bytes, but a smaller number may be read, possibly zero. The number of bytes actually read is returned as an integer.
    In other words... when you use read() and you request say 1024 bytes, you are not guaranteed to get that many bytes. You may get less. You may even get none at all.
    Supposing you want to read length bytes from a stream into a byte array, here is how you do it.int bytesRead = 0;
    int readLast = 0;
    byte[] array = new byte[length];
    while(readLast != -1 && bytesRead < length){
      readLast = inputStream.read(array, bytesRead, length - bytesRead);
      if(readLast != -1){
        bytesRead += readLast;
    }And then the matter of write()...
    http://java.sun.com/j2se/1.3/docs/api/java/io/OutputStream.html#write(byte[])
    write(byte[] b) will always attempt to write b.length bytes, no matter how many bytes you actually filled it with. All you C/C++ converts... forget all about null terminated arrays. That doesn't exist here. Even if you only read 2 bytes into a 1024 byte array, write() will output 1024 bytes if you pass that array to it.
    You need to keep track of how many bytes you actually filled the array with and if that number is less than the size of the array you'll need pass this as an argument.
    I'll make another post about this... once and for all.
    /Michael

  • How to create a jar having the contents of the jar in a byte array?

    Hi,
    I have a server and client application. My server returns the contents of the jar in the form of byte array to the client on a particluar method call. Now at the client end, i want to reconstruct the jar to be used. How do I do this?
    The server uses the JarInputStream to read the contents of the jar to be returned. I have tried using the JarOutputStream, but looks like this works fine if we have spearate class files to be added to the jar. Now that I have the contents of the jar itself, how do i recreate the jar?
    Can anyone please help me with this?
    Thanks
    Rajani

    Have you ever gotten the raw byte copy to work? If so, how?
    I download a jar via InputStream and save into a jar file via fileoutputstream. It always gets corrupted in the process. The new Jar file has the exact same number of bytes, but doesn't get past the Manifest on a -tvf. In fact, Winzip can open it fine, but can't extract. So close...yet so far.
    Here is a snapshot of my code:
    BufferedInputStream data1=new BufferedInputStream(con.getInputStream());
    DataInputStream data=new DataInputStream(data1);
    StringBuffer buf=new StringBuffer();
    try{
    while((theChar=data.read()) != -1)
    { buf.append((char)theChar); }
    } catch (Exception z){ logger.info("UpdateThread.read Done Reading jar file");}
    data.close();
    File newFile = new File("C:/MyJar.jar");
    FileOutputStream outstream2 = new FileOutputStream(newFile);
    DataOutputStream outstream1 = new DataOutputStream(outstream2);
    BufferedOutputStream outstream = new BufferedOutputStream(outstream1);
    byte [] bytes = buf.toString().getBytes();
    logger.info("Bytes of new Jar file = " + bytes.length);
    int i;
    for(i=0;i<bytes.length;i++){
    outstream.write(bytes);
    outstream1.close();
    outstream.close();
    Any ideas where I'm going wrong?

  • How to write data to an XML file present under application server

    frnds: can ne one tell me, how to write data in to a file, which is present under a application server
    Ex: i want to write a string data in to a file test.txt which is present under "http://localhost:8080/<some_webapp>/test.txt"
    Note:i have deploted a service<some_webapp> under Tomcat/webapps dir

    Very simple. A servlet can writes to that file if it has the good rights.
    In the servlet get (or post) method, use a code like this:
    import java.io.*;
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    try {
    String filePath = this.getServletContext().getRealPath("/text.txt");//See http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
             PrintWriter writer = new PrintWriter (filePath);
            //or BufferedWriter out = new BufferedWriter(new FileWriter(filePath));
            writer .println("aString");
           writer.flush();
            writer .close();
        } catch (Exception e) {
           e.printStackTrace();
    }Hope That Helps

  • Reading an XML file and write the contents to another xml file in java

    Hi,
    I am new to xml parsing.My requirement is that I am getting a message (xml) using ibm MQ in the ByteArrayInputStream format.I have to read this xml message and write to another file.
    I am creating a POC for this.
    First I used simple reading and writing concept but the output is "java.io.FileInputStream@3e25a5 "
    Sample xml file
    - <Client>
    <ClientId>1234</ClientId>
    <ClientName>STechnology</ClientName>
    <DTU_ID>567</DTU_ID>
    <ClientStatus>ACTIVE</ClientStatus>
    - <LEAccount>
    <ClientLE>678989</ClientLE>
    <LEId>56743</LEId>
    - <Account>
    <AccountNumber>9876543678</AccountNumber>
    </Account>
    </LEAccount>
    - <Service>
    <Cindicator>Y2Y</Cindicator>
    <PrefCode>980</PrefCode>
    <BSCode>876</BSCode>
    <MandatoryContent>MSP</MandatoryContent>
    </Service>
    </Client>
    code:
    import java.io.ByteArrayInputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    public class ByteArrayInputStreamToXml {
         public static void main(String srg[]) throws IOException{
              InputStream inputStream= new FileInputStream("C:\\soft\\test2\\sample1.xml");
              byte currentXMLBytes[] = inputStream.toString().getBytes();
              ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(currentXMLBytes);
              OutputStream out = new FileOutputStream("C:\\soft\\test\\data.xml");
              int read=0;
              byte[] bytes = new byte[1024];
              while((read = byteArrayInputStream.read(bytes))!= -1){
              out.write(bytes, 0, read);
              out.write( '\n' );
              inputStream.close();
              out.flush();
              out.close();
              System.out.println("New file created!");
    Please suggest me how can I use DOM/SAX parser ,I can see several code on net for reading xml file using SAX/DOM parser but writing an xml file after reading it using ByteArrayInputStream I am not getting .A help through some example Link will also be helpful for me.
    Thanks
    Sumit
    Edited by: user8687839 on Apr 30, 2012 2:37 AM
    Edited by: user8687839 on Apr 30, 2012 2:43 AM

    Thanks I got the result.
    package com.sumit.collections;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    public class ByteArrayInputStreamToXml {
         public static void main(String srg[]) throws IOException{
              InputStream inputStream= new FileInputStream("C:\\soft\\test2\\sample1.xml");
              ByteArrayOutputStream buffer = new ByteArrayOutputStream();
              int nRead; byte[] data = new byte[1024];
              while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
              buffer.write(data, 0, nRead); } buffer.flush();
              byte currentXMLBytes[]= buffer.toByteArray();
              /* byte currentXMLBytes[] = inputStream.toString().getBytes();*/
              ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(currentXMLBytes);
              OutputStream out = new FileOutputStream("C:\\soft\\test\\data.xml");
              int read=0;
              byte[] bytes = new byte[1024];
              while((read = byteArrayInputStream.read(bytes))!= -1){
              out.write(bytes, 0, read);
              out.write( '\n' );
              inputStream.close();
              out.flush();
              out.close();
              System.out.println("New file created!");
    }

  • Using Swing applet to write data to file on SERVER

    Hello,
    I'm in the process of writing an applet using Swing (SDK v1.4.2). Here's the deal. The JApplet calls a JPanel, which will be used by customers on my site to enter data. I'm adding a <Save> button to the "form" which is supposed to write data to a file on the server (in order to preserve the customer's preferences).
    Please note that I am NOT attempting to write data to the customer's hard disk. That requires digital certificates, etc. which I am trying to avoid for now.
    Instead, I am using the URL class to access the file:
    URL page = new URL("http://www.whatever.com/mycustomers/preferences.txt")
    I then use the URLConnection class to establish the connection:
    URLConnection conn = this.page.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.connect();
    etc...
    I've created a text file (preferences.txt) on my web site. Using the classes InputStreamReader, BufferedStreamReader, and StringBuffer, I can successfully read the file into a JOptionPane in my applet.
    The problem comes when I try to write data TO this file. I know the file exists because the applet can read it. I've set the permissions on the file to 666. I've got all of the appropriate syntax within a try statment that catches an IOException. I also have JOptionPanes all over the place to let me know where the program is. I've tried different combinations of output streams like BufferedWriter, BufferedOutputStream, StringWriter, but the file does not get updated. When the applet runs, it does not throw any exceptions, not even when I change the URL from "HTTP://www.whatever.com/prefs.txt" to "HTTP:/www.whatever.com/prefs.txt" (only one slash on HTTP, shouldn't I get a MalformedURLException?)
    I apologize for all the background, but I thought you might need it. The bottom line is:
    1) Can an applet write to a file on a remote server (not local hard disk)?
    2) If so, what (if any) caveats are there?
    3) Is there a way to check for file existence or be able to create a new file?
    4) I'm using the HTTP protocol - is there some restriction that prevents an applet from writing to a file using that protocol? If so, is there a workaround?
    5) Assuming that creating/writing a file using the method I've described is possible, what would be the appropriate output streams to use? (Currently, I'm using OutputStreamWriter with BufferedWriter).
    I've been struggling with this for a while. Any help/suggestions would be appreciated.
    Thanks
    P.S. I also posted this message on the Applet development forum, but I've received no response as of yet.

    Http servers support PUT as a mechanism to upload data to a specified URL. Get on the other hand which is what most people are familiar with is how you retrieve that data. The basic URLConnection is an abstraction of the Http connection which can be used for GET and POST operations by default based on doInput(true|false).. If you which to use any of the http methods other than GET|POST you will have to cast the URLConnection to HttpURLConnection so you can gain access to the specific Http functionaility that could not be abstracted.
    Since you are using a hosting service the chances are that you won't be able to use HTTP PUT on their server. Most servers do not support HTTP PUT without configuring them todo so. Now Apache allows localized config through the .htacess file. It might be possible (keep in mind I am not an apache expert) to configure a particular directory to allow HTTP PUT using this .htacess file it may not be possible. You will have to consult the Apache web server documentation for that answer.
    But regardless you can use the HttpURLConnection and the PUT method to send data from your applet to the server. In fact that is the preferred way to do this. If you can not configure your web server to support that method then you will have to develop a Servlet to do it. A servlet has several methods such as doGet(), doPost(), and doPut(). You would override the doPut() method get the URI path create a file and a FileOutputStream to that file, get from the request the inputstream, possibly skip the http headers, and then write byte for byte the incoming data to your OutputStream until you reach the end at which point you would close the OutputStream and send an Http Response of some sort. Typically in HTTP it would be 200 OK plus some web content. You content can be empty so long as your applet recognizes that is what it should expect...
    And away you go...

Maybe you are looking for