Writing image to wbmp file in java

I am having problem writing images to wbmp files by java using the javax.imageio.* class. Though wbmp is present in the list given by writer format names.
String[] writers = ImageIO.getWriterFormatNames();
System.out.println("Can write to -");
for ( String s : writers)
            System.out.println(s);
        }but my code to convert an image format is not working for wbmp files
File in=new File("star.png");
File out=new File("def.wbmp");
File out1=new File("def.jpg");
BufferedImage image;
try {
     image = ImageIO.read(in);
     ImageIO.write(image,"wbmp",out);
     ImageIO.write(image,"jpg",out1);
} catch (IOException e) {}the jpeg file is created successfully but the wbmp file remains empty. can you tell me where the problem is. Or is there some alternative method for image conversion.

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class WirelessPrep {
    private JPanel getContent(BufferedImage image) {
        JPanel panel = new JPanel(new GridLayout(1,0));
        panel.add(wrap(image));
        panel.add(wrap(convert(image)));
        return panel;
    private BufferedImage convert(BufferedImage image) {
        // Convert to BufferedImage.TYPE_BYTE_BINARY
        BufferedImage binary = convert(image, BufferedImage.TYPE_BYTE_BINARY);
        BufferedImage wbmp = null;
        File file = new File("wirelessPrep.wbmp");
        try {
            ImageIO.write(binary, "wbmp", file);
            wbmp = ImageIO.read(file);
        } catch(IOException e) {
            System.out.println("io error: " + e.getMessage());
        return wbmp;
    private BufferedImage convert(BufferedImage src, int type) {
        int w = src.getWidth();
        int h = src.getHeight();
        BufferedImage dst = new BufferedImage(w, h, type);
        Graphics2D g2 = dst.createGraphics();
        g2.drawImage(src, 0, 0, null);
        g2.dispose();
        return dst;
    private JLabel wrap(BufferedImage image) {
        ImageIcon icon = new ImageIcon(image);
        JLabel label = new JLabel(icon, JLabel.CENTER);
        return label;
    public static void main(String[] args) throws IOException {
        String path = "images/bison.jpg";
        BufferedImage image = ImageIO.read(new File(path));
        JPanel panel = new WirelessPrep().getContent(image);
        JOptionPane.showMessageDialog(null, panel, "", -1);
}

Similar Messages

  • Downloading images and audio file using java

    Dear All
    I have a directory on my webserver which contains images,audio files and many other data files.
    I want to download all the file but the problem is when i download image and save it, it is not viewable. I dont want to use Image class as i may have to downlaod audio files too. Please guis which stream shouldi open to download any kind of content using same code.
    Thanks in advance. And if u have some example please let me know
    Regards
    Jafery

    downloading images and audio file using java -------------------------------
    how to write it back to dataoutputstremI don't understand what you are talking about.
    Server: DataOutputStream -> Client: DataInputStream -- the two is a pair.

  • Writing into a jar file through Java program

    Is there a way to get a file from a jar (for ex. a properties file) make changes to it on the fly and write the same file back to the jar through a Java program?

    I cannnot give u exact code as i am bit busy..but i am giving close to exact
    below is code for reading contents of jar file
    import java.io.*;
    import java.util.jar.*;
    public class JarRead {
    public static void main (String args[])
    throws IOException {
    if (args.length != 2) {
    System.out.println(
    "Please provide a JAR filename and file to read");
    System.exit(-1);
    JarFile jarFile = new JarFile(args[0]);
    JarEntry entry = jarFile.getJarEntry(args[1]);
    InputStream input = jarFile.getInputStream(entry);
    process(input);
    jarFile.close();
    private static void process(InputStream input)
    throws IOException {
    InputStreamReader isr =
    new InputStreamReader(input);
    BufferedReader reader = new BufferedReader(isr);
    String line;
    while ((line = reader.readLine()) != null) {
    System.out.println(line);
    reader.close();
    now here say u have test.jar which contains test.txt (file)
    then
    java JarRead test.jar test.txt
    will print content of text.txt
    now in ur case u write content of each file in some other file modify it there and then create a jar file from those files using jaroutput stream .....
    this may not be all clear ..but what to do..bit busy...u are welcomed to make changes in above stratergy....n queries if any after using above stratergy and/or your great brain...

  • Problem in writing into the excel file using java code

    Hai ,
    I will be getting the data as a string and i am writing into the excel file. the problem is .if it has numeric values even now i will writing as a string data ,at this time i am getting the message in the excel file as "Number in the cell is formatted as text".
    I need to remove this thru my code..but i can write only as a string .
    To write in a excel file ,i used HSSFWorkbook.

    just check out
    http://www.andykhan.com/

  • Problem writing image(Blob) to file

    Hi ,
    I'm trying to write image to file. The Image(26KB) is stored in database as BLOB. I have to change this to CLOB because when I try to write to file its writing all junk data. So I converted BLOB to CLOB then I try to write its giving me error.
    ORA-21560 :argument string is null, invalid, or out of range
    Cause: The argument is expecting a non-null, valid value but the argument value passed in is null, invalid, or out of range. Examples include when the LOB/FILE positional or size argument has a value outside the range 1 through (4GB - 1), or when an invalid open mode is used to open a file, etc.
    Action: Check your program and correct the caller of the routine to not pass a null, invalid or out-of-range argument value.
    The size of IMAGE after coverting to CLOB is 21102 bytes which is between the range.
    Here is how my code looks like:
    DECLARE
    f UTL_FILE.file_type;
    l_blob_len INTEGER;
    buffer VARCHAR2 (32767);
    buffer_size CONSTANT BINARY_INTEGER := 32767;
    amount BINARY_INTEGER;
    offset NUMBER (38);
    l_blob BLOB;
    l_clob CLOB := 'x';
    l_dest_offsset INTEGER := 1;
    l_src_offsset INTEGER := 1;
    l_lang_context INTEGER := DBMS_LOB.default_lang_ctx;
    l_warning INTEGER;
    BEGIN
    SELECT blobdata
    INTO l_blob
    FROM lob_table ip
    WHERE ip.id = 2;
    DBMS_LOB.converttoclob (dest_lob => l_clob,
    src_blob => l_blob,
    amount => DBMS_LOB.lobmaxsize,
    dest_offset => l_dest_offsset,
    src_offset => l_src_offsset,
    blob_csid => DBMS_LOB.default_csid,
    lang_context => l_lang_context,
    warning => l_warning);
    amount := buffer_size;
    offset := 1;
    f := UTL_FILE.fopen ('IN_FILE_LOC', 'something.doc', 'w');
    WHILE amount >= buffer_size
    LOOP
    DBMS_OUTPUT.put_line ('buffer_size');
    DBMS_LOB.READ (l_clob,
    amount,
    offset,
    buffer);
    UTL_FILE.PUT (f, buffer);
    UTL_FILE.FFLUSH (f);
    END LOOP;
    UTL_FILE.fclose (f);
    END;
    Please tell me what did I do wrong.

    Try this posts
    http://www.oracle-base.com/articles/9i/ExportBlob9i.php
    http://download.oracle.com/docs/cd/B10500_01/appdev.920/a96591/adl06faq.htm

  • Writing or modifying text files in java

    Dear all,
    I have the next text file:
    goods: 5
    bids: 4
    % num, price, good, good, ..., good, #
    0 2075 1 4 #
    1 3000 1 2 3 4 #
    2 520 3 #
    3 3000 2 3 4 #
    I have to modify or create the file above, using output data from one java program. For example, The output of my java program in the next execution is:
    goods: 8
    and price (0) changes from 2075 to 2078.
    so, using this output data my java program should write (create or modify) the next text file with the changes:
    goods: 8
    bids: 4
    % num, price, good, good, ..., good, #
    0 2078 1 4 #
    1 3000 1 2 3 4 #
    2 520 3 #
    3 3000 2 3 4 #
    I have tried using: output.write( objetc );
    but it doesn't work as I need :( .
    Somebody can help me or give me some idea?
    Thanks,
    Andrea

    This is the code:
    File testFile = new File("D:\\result1.txt");
    setContents(testFile, " bla bla bla (few characters) ");
    static public void setContents(File aFile, String aContents)
    throws FileNotFoundException, IOException {
    try {
    //use buffering
    output = new BufferedWriter( new FileWriter(aFile) );
    output.write( aContents );
    finally {
    //flush and close both "output" and its underlying FileWriter
    if (output != null) output.close();
    I mean, this code dont work because it let me write few characters only. I need to write the whole file:
    goods: 8
    bids: 4
    % num, price, good, good, ..., good, #
    0 2078 1 4 #
    1 3000 1 2 3 4 #
    2 520 3 #
    3 3000 2 3 4 #
    with the special characters as (#).
    Sorry, if it post is not clear.
    Thanks.

  • Reading/writing PDF files using JAVA

    how to read/write a PDF file using java,
    while i read a pdf file using BUfferedReader class it gives a list of char. which is not readable.
    how to convert those files to readable format.?
    is there any special class for doin that.?
    plz explain..?

    is there any special class for doin that.?Yes, I'm sure Google knows a few libraries that ca do that.

  • Writing Text Files in Java

    hello!
    i am creating an Applet game and I would like to create Rankings.
    So, i need to take data from java and transfer them into HTML. At my
    university's book says that everytime we open a file to write in it, if there are
    already data, Java removes them and then writes the new ones. But I want
    a static file where Java can write the updated rankings and HTML can take
    them and use them in site. Is there any way to achive that guys?
    If i wasn't clear, i just want a way to make Java not to delete any data in a file
    everytime it needs to write something in it!
    thanks alot!

    hello!
    i am creating an Applet game and I would like to
    create Rankings.
    So, i need to take data from java and transfer them
    into HTML. At my
    university's book says that everytime we open a file
    to write in it, if there are
    already data, Java removes them and then writes the
    new ones. But I want
    a static file where Java can write the updated
    rankings and HTML can take
    them and use them in site. Is there any way to achive
    that guys?
    If i wasn't clear, i just want a way to make Java not
    to delete any data in a file
    everytime it needs to write something in it!
    thanks alot!There are a number of problems here.
    First of all you can always append to a file, but that's not actually what you want to do.
    Second you can read the whole file in, find the values you want, change them and write the whole file back. This is more of what you want to do but HTML is not the best choice for doing this.
    But the most fundamental problem is that you do not write to files of any kind in an Applet.

  • Problem in writing image

    Hi,
    I have a problem in writing png.
    Here's my code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.image.BufferedImage;
    import java.awt.image.RenderedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class ProvaImg extends JPanel{
         private static JFrame frame;
          * @param args
         public static void main(String[] args) {
              frame = new JFrame ();
              frame.setSize(100,100);
              ProvaImg pi=new ProvaImg();
              frame.add(pi);
              frame.setVisible(true);
              //PROBLEM HERE
              frame.setVisible(false);
         public ProvaImg(){
              super();
             // Returns a generated image.
             public void paintComponent(Graphics g) {
                 int width = 100;
                 int height = 100;
                 // Create a buffered image in which to draw
                 BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                 Graphics2D g2d=(Graphics2D)g;
                 // Create a graphics contents on the buffered image
                  g2d = bufferedImage.createGraphics();
                 // Draw graphics
                 g2d.setColor(Color.white);
                 g2d.fillRect(0, 0, width, height);
                 g2d.setColor(Color.black);
                 g2d.fillOval(0, 0, width, height);
                 // Graphics context no longer needed so dispose it
                 g2d.dispose();
                  try {
                      // Save as PNG
                      File file = new File("newimage.png");
                      System.out.println("png");
                      ImageIO.write(bufferedImage, "png", file);
                  } catch (IOException e) {
         }If I comment line after
    //PROBLEM HERE
    it works, otherwise no.
    Is there a possibility to close panel when image has been written?
    Thanks in advance
    Bye

    No,
    I try to explain better:
    In my real application (not this simple example) I compose an image by the union of many little gifs. Then I have to save the result in a unique image. It's for this that I've overridden paintComponent(), so , after having painted all gifs, I save composite image to a png one.
    This function is activated from a main application, and I don't want to show too much to user, so I try to make this by using a popup frame that disappear quickly.
    I hope to having been as clear as possible.
    I hope to have chosen the best solution too
    Bye and thanks
    Edited by: giuseppe_italiano on Nov 21, 2007 3:35 AM

  • How to print a text file using Java

    How can I print a text file using Java without converting the output to an image format. Is there anyway I can send the characters in the text file as it is for a print job? I did get a listing doing this ... but that converted the text to an image format before printing....
    THanks,.

    Hi I had to write a print api from scratch, and I did not convert the output to image. Go and read up on the following code. I know there is a Tutorial on Sun about the differant sections of the snippet.
    private void printReport()
         Frame tempFrame = new Frame(getName());
         PrintJob printerJob = Toolkit.getDefaultToolkit().getPrintJob(tempFrame, "Liesltext", null);
         Graphics g = printerJob.getGraphics();
                    //I wrote the method below for calculations
         printBasics(g);
         g.dispose();
         printerJob.end();
    }This alone wont print it you have to do all the calculations in the printBasics method. And as I said I wrote this from scratch and all I did was research first the tutorial and the white papers
    Ciao

  • Problem in reading no. of files and writing into a single file

    Hi,
    Iam with Problem in reading no. of files and writing into a single file....
    Iam reading no. of files stored in local directory.......
    Iam able to read and print the data in files successfully....but while writing..only first file is being written...and the next files are not written in my output file...
    plz tell me my mistake....I hope Iam doing some mistake while writing into file...PLz help.....
    Basically my code structure is like this....
    import java.io.*;
    import java.util.regex.*;
    import java.util.*;
    import java.text.*;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    class Writing {
    public static void main(String args[]) throws Exception {
              FileOutputStream fileOut = new FileOutputStream("ServerResult.xls"); //my output file
              int counter = 1;
              File dir = new File("C:/Perform/ServerLogs");
              String[] children = dir.list();
              if( children == null)
                   System.out.println("The Directory mentioned does not exist");
              else {
                   for (int fileNo = 0; fileNo < children.length; fileNo++ ) {        //Files iteration starts
                        String filename = children[fileNo];
              File logFile = new File(filename);
    FileReader logFileReader = new FileReader(logFile);
    BufferedReader logReader = new BufferedReader(logFileReader);
    StringBuffer sBuf = new StringBuffer(5000);
              HSSFWorkbook wb = new HSSFWorkbook();          
              HSSFSheet sheet = wb.createSheet();
              HSSFRow rowTitle;
              HSSFRow rowReq;
              HSSFRow rowRes;
    String aLine = null;
    boolean skip = false;
    boolean readed = false;
    boolean initReq = false;
              boolean flag = false;
    long requestTime = 0;
    long responseTime = 0;
    long recdTime = 0;
    long sentTime = 0;
              long hasTime = 0;
              long presentTime = 0;
              int hasCalls = 0;
    Pattern startMessage = Pattern.compile("^<MESSAGE.*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
    Pattern requestMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"RequestMsg.\".*ID=\".*_"+args[0]+"\".*<ActName>(.*)</ActName>.*", Pattern.DOTALL);
    Pattern requestMessage1 = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"RequestMsg.\".*ID=\".*_"+args[0]+"\".*<Svc id=\"(.*)\">.*", Pattern.DOTALL);
    Pattern responseMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
    Pattern initMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"HostConnInit\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
    Pattern initResMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\"null\".*", Pattern.DOTALL);
    Pattern initResIDMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\"null\".*<IATA>"+args[0]+"</IATA>.*", Pattern.DOTALL);
              Pattern sentMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"DCMsgSentInfo\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
              Pattern rcvdMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"DCMsgRcvdInfo\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    DecimalFormat dcf = new DecimalFormat("########.##");
    String actName = "";
              if (fileNo ==0)
              rowTitle = sheet.createRow((short)0);
              rowTitle.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)0).setCellValue("Req/Res");
              rowTitle.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)1).setCellValue("Action");
              rowTitle.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)2).setCellValue("Server Time(in ms)");
              rowTitle.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)3).setCellValue("Request Vs Response Time in Server(in ms)");
              rowTitle.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)4).setCellValue("Time Taken By HAS/HOST(in ms)");
              rowTitle.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)5).setCellValue("No. of HAS calls");
              rowTitle.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
              rowTitle.createCell((short)6).setCellValue("Data Size");
              //wb.write(fileOut);
    while((aLine=logReader.readLine()) != null) {
    if(aLine.startsWith("<MESSAGE TYPE=\"EVENT\"")) {
    Matcher m = startMessage.matcher(aLine);
    if(m.find()) {
    sBuf.setLength(0);
    sBuf.append(aLine);
    skip = false;
    initReq = false;
    m = initMessage.matcher(aLine);
    if(m.find()) {
    initReq = true;
    } else {
    if(initReq) {
    m = initResMessage.matcher(aLine);
    if(m.find()) {
    sBuf.setLength(0);
    sBuf.append(aLine);
    skip = false;
    } else if(aLine.startsWith("</MESSAGE>")) {
    if(!skip) {
    sBuf.append(aLine);
    readed = true;
    } else if(!skip){
    sBuf.append(aLine);
    if(!skip && readed) {
    String tempStr = sBuf.toString();
    if(tempStr.length() > 0) {
    boolean reqMatched = false;
    Matcher m = null;
    if(initReq) {
    m = initMessage.matcher(tempStr);
    actName = "Intialization";
    } else {
    m = requestMessage.matcher(tempStr);
    String time = "";
    if(m.find()) {
    reqMatched = true;
    for (int i=1; i<=m.groupCount(); i++) {
    String groupStr = m.group(i);
    if(i == 1) {
    time = groupStr;
    } else if(i == 2) {
    actName = groupStr;
    } else if(!initReq){
    m = requestMessage1.matcher(tempStr);
    if(m.find()) {
    reqMatched = true;
    for (int i=1; i<=m.groupCount(); i++) {
    String groupStr = m.group(i);
    if(i == 1) {
    time = groupStr;
    } else if(i == 2) {
    actName = groupStr;
    if(time.length() > 0 ) {
    try{
    requestTime = sdf.parse(time).getTime();
    }catch(Exception ex){}
    System.out.println("Request,"+actName+","+time+",,,,"+dcf.format(((double)time.length()/1024.0))+"K");
                                  //bw.write("Request,"+actName+","+time+",,,,"+dcf.format(((double)time.length()/1024.0))+"K");
                                  String reqDataSize = dcf.format(((double)time.length()/1024.0))+"K" ;
                                  rowReq = sheet.createRow((short)counter);
                                       rowReq.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)0).setCellValue("Request");
                                       rowReq.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)1).setCellValue(actName);
                                       rowReq.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)2).setCellValue(time);
                                       rowReq.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)3).setCellValue("");
                                       rowReq.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)4).setCellValue("");
                                       rowReq.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)5).setCellValue("");
                                       rowReq.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
                                       rowReq.createCell((short)6).setCellValue(reqDataSize);
                                       counter = counter +1;
                                       System.out.println("counter is "+counter);
                             Matcher l = sentMessage.matcher(tempStr);
                             Matcher k = rcvdMessage.matcher(tempStr);
                   if(l.find()) {
                                            for (int i=1; i<=l.groupCount(); i++) {
         String groupStr2 = l.group(i);
    try{
    sentTime = sdf.parse(groupStr2).getTime();
    }catch(Exception ex){}
                        if(k.find())
                                                 for(int j=1;j<=k.groupCount(); j++) {
                                                 String groupStr1 = k.group(j);
                                                 try{
    recdTime = sdf.parse(groupStr1).getTime();
    }catch(Exception ex){}
                                                 presentTime = (recdTime - sentTime);
                                                 hasTime = hasTime + presentTime;
                                                 hasCalls = hasCalls +1;
    if(!reqMatched) {
    if(initReq) {
    m=initResIDMessage.matcher(tempStr);
    } else {
    m=responseMessage.matcher(tempStr);
    if(m.find()) {
    for (int i=1; i<=m.groupCount(); i++) {
    String groupStr = m.group(i);
    try{
    responseTime = sdf.parse(groupStr).getTime();
    }catch(Exception ex){}
                                                 String resDataSize = dcf.format(((double)tempStr.length()/1024.0))+"K" ;
                                                 rowRes = sheet.createRow((short)(counter));
                                                 rowRes.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
                                                 rowRes.createCell((short)0).setCellValue("Response");
                                                 rowRes.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
                                                 rowRes.createCell((short)1).setCellValue(actName);
                                                 rowRes.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
                                                 rowRes.createCell((short)2).setCellValue(groupStr);
                                                 rowRes.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                                 rowRes.createCell((short)3).setCellValue((responseTime - requestTime));
                                                 rowRes.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                                 rowRes.createCell((short)4).setCellValue(hasTime);
                                                 rowRes.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
                                                 rowRes.createCell((short)5).setCellValue(hasCalls);
                                                 rowRes.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
                                                 rowRes.createCell((short)6).setCellValue(resDataSize);
                                                 hasTime = 0;
                                                 hasCalls = 0;
                                                 counter = counter + 1 ;
    sBuf.setLength(0);
    readed = false;
              wb.write(fileOut);
              } // End of for (int fileNo = 0; fileNo < children.length; fileNo++ )
    }     //End of else
              fileOut.close();
    } //End of public static void main
    } // End of Class

    First of all, use [code]-tags to make your code readable, please.
    I didn't do a complete inspection of your code (because it's too much and unreadable as it is) and I don't know POI, but creating a new HSSFWorkbook for each input file sounds fishy to me ... try re-using the workbook and just creating a new sheet in each iteration.

  • 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!");
    }

  • How to create the ini file for java programms

    hi all,
    I have one problem that is ...
    In my project I am using the JDBC connection ...
    in this I am connecting different connections (means differenet usernames and passwords)...
    for this evrey time I have to change the username and password in the
    hardcode ...
    I think that some ini file are there in java ...
    So if anyone knows about use of ini files in java please
    send me..
    thanks........

    In java they are called properties files.
    Look at java.util.Properties which provides methods for reading, writing, etc.

  • How to display pdf file with java code?

    Hi All,
    i have a jsp pagein that page if i click one icon then my backing bean method will call and that method will create pdf document and write some the content in that file and now i want to display that generated pdf document.
    it should look like you have pressed one icon and it displayed pdf file to you to view.
    java code below:
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();
    HttpServletResponse resp = (HttpServletResponse) ec.getResponse();
    resp.setHeader("Content-Disposition", "filename=\"" + temppdfFile);
    resp.encodeRedirectURL(temppdfFile.getAbsolutePath());
    resp.setContentType("application/pdf");
    ServletOutputStream out = resp.getOutputStream();
    ServletUtils.returnFile(temppdfFile, out);
    out.flush();
    and above temppdfFile is my generated pdf file.
    when i am executing this code, it was opening dialog box for save and cancel for the file, but the name of the file it was showing me the "jsp file name" with no file extention (in wich jsp file i am calling my backing bean method) and type is "Unknown File type" and from is "local host"
    it was not showing me open option so i am saving that file then that file saved as a pdffile with tha name of my jsp file and there is nothing in that file(i.e. empty file).
    what is the solution for this. there is any wrong in my code.
    Please suggest me.
    Thanks in advance
    Indira

    public Object buildBarCodes() throws Exception
    File bulkBarcodes = null;
    String tempPDFFile = this.makeTempDir();
    File tempDir = new File("BulkPDF_Files_Print");
    if(!tempDir.exists())
    tempDir.mkdir();
    bulkBarcodes = File.createTempFile
    (tempPDFFile, ".pdf", tempDir);
    //bulkBarcodes = new File(tempDir, tempPDFFile+"BulkBarcode"+"."+"pdf");
    if(!bulkBarcodes.exists())
    bulkBarcodes.createNewFile();
    Document document = new Document();
    FileOutputStream combinedOutput = new FileOutputStream(bulkBarcodes);
    PdfWriter.getInstance(document, combinedOutput);
    document.open();
    document.add(new Paragraph("\n"));
    document.add(new Paragraph("\n"));
    Image image = Image.getInstance(bc.generateBarcodeBytes(bc.getBarcode()));
    document.add(image);
    combinedOutput.flush();
    document.close();
    combinedOutput.close();
    FacesContext facesc = FacesContext.getCurrentInstance();
    ExternalContext ec = facesc.getExternalContext();
    HttpServletResponse resp = (HttpServletResponse) ec.getResponse();
    resp.setHeader("Content-Disposition", "inline: BulkBarcodes.pdf");
    resp.encodeRedirectURL(bulkBarcodes.getAbsolutePath());
    resp.setContentType("application/pdf");
    resp.setBufferSize(10000000);
    ServletOutputStream out = resp.getOutputStream();
    ServletUtils.returnFile(bulkBarcodes, out);
    out.flush();
    return "success";
    This is my action method which will call when ever i press a button in my jsp page.
    This method will create the barcode for the given barcode number and write that barcode image in pdf file
    (i saw that pdf file which i have created through my above method, This PDF file opening when i was opening manually and the data init that is also correct means successfully it writes the mage of that barcode)
    This method taking the jsp file to open because as earlier i said it was trying to open unknown file type document and i saved that file and opended with editplus and that was the jsp file in which file i am calling my action method I mean to say it was not taking the pdf file which i have created above it was taking the jsp file

  • Sorting Names in a text file using java program

    h1. Deleting numbers in a text file, sorting the names  and writing in to a new file
    h2. Sample data
    =================
    71234 RAJA
    89763 KING
    89877 QUEEN
    ==================
    h2. Java Program
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileWriter;
    import java.io.InputStreamReader;
    import java.io.Writer;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    class Sortnames { 
    public static void main(String args[]) { 
    try { 
    ArrayList storeWordList = new ArrayList();
    ArrayList storeWordList2 = new ArrayList();
                   int i;
    char c;
                   String inputfile = "names_konda.txt";
                   String tempfile = "newdatafile.txt";
                   String outputfile = "sortedoutput.txt";
                   StringBuffer strBuff=null;
    Writer output = null;
    File file =null;
                   Writer sortedoutput = null;
    boolean select =false;
                   //*********************************************** Reading data from Input file     
    FileInputStream fstream = new FileInputStream(inputfile);
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null) { 
    storeWordList.add(strLine);
    //Close the input stream
    in.close();
                   //*********************************************** Adding only alphabets to buffer and writing to file
                   file= new File(tempfile);
                   output = new BufferedWriter(new FileWriter(file));
    strBuff = new StringBuffer();
    for (Iterator iter = storeWordList.iterator(); iter.hasNext();) { 
         String s = (String) iter.next();
                        //System.out.println("String "+s);
         for (i = 0; i < s.length() ; i++)
    c = s.charAt(i);
    if (Character.isLetter(c)) {
    strBuff.append(c);
                        strBuff.append("\n");
    String myout = strBuff.toString();                
         output.write(myout);
         output.close();
         //============================================== Reading the created file,Sorting and placing in Collections
                   FileInputStream fstream2 = new FileInputStream(tempfile);
    // Get the object of DataInputStream
    DataInputStream in2 = new DataInputStream(fstream2);
    BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
    String strLine2;
    //Read File Line By Line
    while ((strLine2 = br2.readLine()) != null) {                 
    storeWordList2.add(strLine2);
    Collections.sort(storeWordList2);
                   //===================================================
    File sortedfile = new File(outputfile);
    sortedoutput = new BufferedWriter(new FileWriter(sortedfile));
    for(int m=0; m<storeWordList2.size(); m++)
         if (storeWordList2.get(m).toString().trim().length() > 0)
              sortedoutput.write(storeWordList2.get(m).toString());
                        sortedoutput.write("\n");     
    sortedoutput.close();
    System.out.println("Names Sorted SUCCESFULLY");
    br.close();
    br2.close();
    in.close();
    fstream.close();
    fstream2.close();
                   ///==========================================
                   File f1 = new File(tempfile);
                   boolean success = f1.delete();
                   if (!success){
                        System.out.println("failed deletion ");
                        System.exit(0);
                        }else{
                        System.out.println("deleted");
                   // ==========================================
    } catch (Exception e) {//Catch exception if any 
    System.out.println("Error: " + e);
    h2. Thanks and regards
    h1. BalaNagaRaju.M
    h1. [email protected]

    Do you have a question? Also see the sticky welcome post on how to post formatted code.

Maybe you are looking for

  • How do I recover from a hard drive crash??

    I had an extreme hard disk crash with all of my images and the recovery service could only recover a few of the images.  Here's my problem - when I originally imported my Nikon images (.NEF format) into LR, I created a new .dng format and saved the .

  • How to install apps on sd card in Windows 8.1

    Why is it not possible to install apps from the Windows Store on to sd cards in the Windows 8.1 OS???? This is absolutely frustrating because you guys obviously blocked the functionality to change it since Windows 8, and since I've updated my tablet

  • Vendor payments report for a month

    Dear all, is there any built report that would show all the vendor payments in a month with the date it has been debited our account? I tried with FAGLL03, but the date of the ZP document created by F110 can be different from the date of the ZR docs,

  • How to remove dark areas from scanned book PDFs?

    Hello, When scanning chapters from a book, I get large dark areas where the scanner picks up 'dead space' from the spine and around the perimeter of the book. I have been able to remove these using the 'Redaction' tool but when I go to save the PDF t

  • I updated to mountain lion and now mail cannot connect to my server

    I updated to mountain lion and now mail cannot connect to my server.  It says check your user name and password are correct.  Well they are, and were.  Nothing has changed except the mac OS.  Has anyone else suffered this and knows a way around it?