Split XML in Multiple XML files with Java Code

Hi guys , i have following xml file as input ....
<?xml version="1.0" encoding="ISO-8859-1"?>
<T0020
xsi:schemaLocation="http://www.safersys.org/namespaces/T0020V1 T0020V1.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.safersys.org/namespaces/T0020V1">
<INTERFACE>
<NAME>SAFER</NAME>
<VERSION>04.02</VERSION>
</INTERFACE>
<TRANSACTION>
<VERSION>01.00</VERSION>
<OPERATION>REPLACE</OPERATION>
<DATE_TIME>2009-09-01T00:00:00</DATE_TIME>
<TZ>CT</TZ>
</TRANSACTION>
<IRP_ACCOUNT>
<IRP_CARRIER_ID_NUMBER>274845</IRP_CARRIER_ID_NUMBER>
<IRP_BASE_COUNTRY>US</IRP_BASE_COUNTRY>
<IRP_BASE_STATE>AR</IRP_BASE_STATE>
<IRP_ACCOUNT_NUMBER>55002</IRP_ACCOUNT_NUMBER>
<IRP_ACCOUNT_TYPE>I</IRP_ACCOUNT_TYPE>
<IRP_STATUS_CODE>100</IRP_STATUS_CODE>
<IRP_STATUS_DATE>2007-11-06</IRP_STATUS_DATE>
<IRP_UPDATE_DATE>2009-08-03</IRP_UPDATE_DATE>
<IRP_NAME>
<NAME_TYPE>LG</NAME_TYPE>
<NAME>A P SUPPLY CO</NAME>
<IRP_ADDRESS>
<ADDRESS_TYPE>PH</ADDRESS_TYPE>
<STREET_LINE_1>1400 N OATS</STREET_LINE_1>
<STREET_LINE_2/>
<CITY>TEXARKANA</CITY>
<STATE>AR</STATE>
<ZIP_CODE>71854</ZIP_CODE>
<COUNTY>MILLER</COUNTY>
<COLONIA/>
<COUNTRY>US</COUNTRY>
</IRP_ADDRESS>
<IRP_ADDRESS>
<ADDRESS_TYPE>MA</ADDRESS_TYPE>
<STREET_LINE_1>P O BOX 1927</STREET_LINE_1>
<STREET_LINE_2/>
<CITY>TEXARKANA</CITY>
<STATE>AR</STATE>
<ZIP_CODE>75504</ZIP_CODE>
<COUNTY/>
<COLONIA/>
<COUNTRY>US</COUNTRY>
</IRP_ADDRESS>
</IRP_NAME>
</IRP_ACCOUNT>
<IRP_ACCOUNT> ..... </IRP_ACCOUNT>
<IRP_ACCOUNT> ..... </IRP_ACCOUNT>
<IRP_ACCOUNT> ..... </IRP_ACCOUNT>
</T0020>
and i want to take this xml file and split it into multiple files through java code like this ...
File1.xml
<T0020>
<IRP_ACCOUNT> ..... </IRP_ACCOUNT>
<IRP_ACCOUNT> ..... </IRP_ACCOUNT>
</T0020>
File2.xml
<T0020>
<IRP_ACCOUNT> ..... </IRP_ACCOUNT>
<IRP_ACCOUNT> ..... </IRP_ACCOUNT>
</T0020>
like wise...
Each xml file contain maximum 10 or 15 IRP_ACCOUNT.
Can somebody please help me ? How can i do it with stax like start element and all ?
thanks in advance.

Ah, sorry, strike that. You want multiple files. I think the easiest way is to simply parse with DOM. [http://www.w3schools.com/xpath/default.asp] . And here [http://www.w3schools.com/xpath/default.asp].
You can output the various XML elements using a PrintWriter or creating a separate DOM document for each file you want to create and serializing that.
- Saish

Similar Messages

  • 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

  • Generation of xml file from java code

    hi,
    I want to manipulate data in a xml file with java code.I have read data from xml file and also changed it. But i am unable to covert it again in xml file from java code. Can you please tell me how i can do this?

    Let me know which parser are you using currently for reading xml files so that i assist you. For now, you can refer to STAX Parser API under this link
    http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP3.html

  • How to modify an existing xml file from java code.

    Hi
    I have worked on creating a new xml file from java code using xmlbeans.But if i try to modify an already existing file using java code I am unable to get errorfree xmlfile.
    For example if xml file(studlist.xml) is as below:
    <?xml version="1.0" encoding="UTF-8"?>
    <StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
         <Student>
              <Name>ram</Name>
              <Age>27</Age>
         </Student>
    <Student>
              <Name>sham</Name>
              <Age>26</Age>
         </Student>
    </StudentList>
    Now suppose i have set name to victor using student.setName,
    and set age to 20 using setAge from javacode,
    the new xml file is as follows:
    <?xml version="1.0" encoding="UTF-8"?>
    <StudentList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="D:\kchaitanya\xmlprac1\abc\Studlist.xsd">
         <Student>
              <Name>ram</Name>
              <Age>27</Age>
         </Student>
    <Student>
              <Name>sham</Name>
              <Age>26</Age>
         </Student>
    </StudentList>
    <Student>
              <Name>victor</Name>
              <Age>20</Age>
         </Student>
    As observed this is not a valid xml file.But how can i modify without any errors?

    I know it's an old post, but I found this while doing a google search for something else, and don't like to leave it un-aswered
    Just in case anyone has a similar problem... In this case the new elements have been appended outside of the root element
    What you need to do is first get the root element and then append the new children to that, there are several ways of getting the root element, which depend on what you want to do with the elements you get back here's a simple (incomplete) way.
    // gets the root element of the specified file (code not shown)
    Element rootElement= new SAXReader().read(file).getRootElement();Then just append the new elements as below (this is non-generic code and would need to be modified for your situation)
    // write a new student element
    Element student = document.createElement("Student");  // creates the new student
    rootElement.appendChild(student); // ***appends it to the root element***
    Element name = document.createElement("Name"); // creates the name element
    name.appendChild(document.createTextNode("Fred")); // adds the name text to the name element
    student.appendChild(name); // appends the name to the student
    Element age= document.createElement("Age"); // creates the age element
    age.appendChild(document.createTextNode("26")); // adds the age text to the age element
    student.appendChild(age); // appends the name to the studentThen flush ya buffers or whatever and write the file
    Edited by: Dream-Scourge on Apr 23, 2008 11:10 AM

  • Splitting TempDB into multiple data files.

    To avoid contention we have to split tempdb into multiple data files. But as for case suppose, there is 20 GB total space is on the drive containing 1 tempdb data file of 15 GB. And I have to create 3 more tempdb data files, and as recommendation all files
    should be of same size.Then how to handle this situation and configure all data files with same size?
    Pranshul Gupta

    But as for case suppose, there is 20 GB total space is on the drive containing 1 tempdb data file of 15 GB. And I have to create 3 more tempdb data files, and as recommendation all files should be of same size.Then how to handle this situation and configure
    all data files with same size?
    So your goal is to have 4 tempdb files, each 5GB?  Below is a sample script to accomplish the task within the 20GB space constraint.
    --reduce size of existing file to 5GB
    ALTER DATABASE tempdb
    MODIFY FILE (NAME='tempdev', Size=5GB);
    DBCC SHRINKFILE('tempdev',5120);
    --add 3 new 5GB files
    ALTER DATABASE tempdb
    ADD FILE (NAME='tempdev2', FILENAME='D:\SqlDataFiles\tempdb2.ndf', Size=5GB);
    ALTER DATABASE tempdb
    ADD FILE (NAME='tempdev3', FILENAME='D:\SqlDataFiles\tempdb3.ndf', Size=5GB);
    ALTER DATABASE tempdb
    ADD FILE (NAME='tempdev4', FILENAME='D:\SqlDataFiles\tempdb4.ndf', Size=5GB);
    Dan Guzman, SQL Server MVP, http://www.dbdelta.com

  • How do I merge multiple Excel files with more than one tab in each file using PowerQuery?

    Hello
    I have 12 Excel (.xlsx) files and each file has three identically named and ordered tabs in them. 
    I know how to merge multiple Excel files in a folder using M (those guides are all over the web) but how do I merge multiple Excel files with multiple (yet identically named and ordered) tabs? Surely it is possible? I just don't know how to do it in M.
    Cheers
    James

    What Laurence says is correct, and probably the best thing to do when the sheets have differing structures. Here is an alternate approach that works well when the sheets all have the same structure.
    When you first open the Excel file from Power Query, you can see its structure in the navigator at the right-hand-side of the screen. If you select the root (which is the filename itself) and click Edit, you'll see all the tabs in the sheet as a single table.
    You can now do filtering based on the Name, Item and Kind values. When you've reduced the set of things down to the sheets you want, select the Data column and say "Remove Other Columns". If the sheets don't have any header rows, you can just click the expand
    icon in the header and you'll be done.
    Otherwise, if the sheets have headers or if some other kind of sheet-level transformation is required against each sheet before doing a merge, you'll have to write some M code manually. In the following example, each sheet has a header row consisting of
    two columns: Foo and Bar. So the only step I need to perform before merging is to promote the first row into a header. This is done via the Table.TransformColumns operation.
    let
        Source = Excel.Workbook(File.Contents("C:\Users\CurtH\Desktop\Test1.xlsx")),
        RemovedOtherColumns = Table.SelectColumns(Source,{"Data"}),
        PromotedHeaders = Table.TransformColumns(RemovedOtherColumns,{{"Data", each Table.PromoteHeaders(_)}}),
        ExpandData = Table.ExpandTableColumn(PromotedHeaders, "Data", {"Foo", "Bar"}, {"Data.Foo", "Data.Bar"})
    in
        ExpandData

  • I can't open or save file with Java Web Start

    Hi,
    i can't open or save file with Java Web Start:
    import java.io.*;
    import java.util.*;
    public class MetaDataFileCreator {
    public String fileNameSpace = null;
    public String fileName = null;
    protected Properties file = null;
    public MetaDataFileCreator(String fileNameSpace, String fileName) {
    this.fileNameSpace = fileNameSpace;
    this.fileName = fileName;
    public void createMetaDataFile() {
    try {
    System.out.println("file METADATA");
    ClassLoader cl = this.getClass().getClassLoader();
    String nameFileMetaData = fileNameSpace + fileName + ".txt";
    FileOutputStream fileOS = new FileOutputStream(cl.getResource(nameFileMetaData).getFile());
    file = new Properties();
    file.setProperty("aaaaa", "aaaa");
    file.store(fileOS, "");
    fileOS.close();
    } catch (Exception e) {
    System.out.println("Error writing metadata-file: " + e);
    System.exit(1);
    e.printStackTrace();
    I have try also to open a file like this:
    ClassLoader cl = this.getClass().getClassLoader();
    file.load(cl.getResourceAsStream(nameFile));
    also like this:
    try {
    fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
    fss = (FileSaveService)ServiceManager.lookup("javax.jnlp.FileSaveService");
    } catch (UnavailableServiceException e) {
    fss = null;
    fos = null;
    System.out.println("Error with JNLP");
    System.exit(1);
    if (fss != null && fos != null) {
    try {
    // get a FileContents object to work with from the
    // FileOpenService
    FileContents fc = fos.openFileDialog(null, null);
    //FileContents newfc2 = fss.saveAsFileDialog(null, null, fc);
    // get the OutputStream and write the file back out
    if (fc.canWrite()) {
    // don't append
    os = fc.getOutputStream(false);
    } catch (Exception e) {
    e.printStackTrace();
    also like this:
    File f = new File((System.getProperty("user.home")+"x.txt").toString());
    FileOutputStream fileX = new FileOutputStream(f);
    OutputX = new PrintWriter(new BufferedWriter(new OutputStreamWriter(fileX, "UTF8")));
    OutputX.println(....
    but it doesn't work with Java Web Start.
    Can someone help me?
    How can I open or save file?
    thank you.
    Sebastiano

    Did you specify <all-permissions/> in your JNLP file? Did you sign your code? What error are you getting?

  • How to use parameter file with java

    Is it possible to use a parameter file with Java, and is there any class/method to make it easy to call and use these parameter from a text file, other than scanning the whole text file manually as we can do normally with visual basic/c++, so we can call the program with the parameter file, like java testing c:\\testing.ini

    If I understand you correctly, you may be looking for a properties file. This is basically a text file that contains pairs of strings in the form:
    parameter1=value1
    parameter2=value2
    parameter3=value3
    ...etc.
    and the values are retrieved using the java.util.Properties class - see:
    http://java.sun.com/j2se/1.3/docs/api/java/util/Properties.html
    Sample use://Call chis method once, to load the props file.
    //props file is called "demo.properties", and is
    //in a directory that is included in the classpath
        private void loadMyProperties() throws Exception
         InputStream stream = getResourceAsStream("/demo.properties");
         if(stream == null)
             throw new Exception("stream is null!");
         demoProperties = new Properties();
         demoProperties.load(stream);
         stream.close();
    // Then you can retrieve properties in your code using:
    String param3 = demoProperties.getProperty("parameter3");
    //...etc

  • SSIS project - read multiple flat files with different formats

    hi all,
    i need to import multiple flat files with different formats into different tables of the sql server database and not able to figure out the best way out in ssis to do so...
    please advise the possible methods in ssis to do so and if possible the process which can be dynamic as file names or columns might change in future.

    Hi AK1987,
    To import flat files with dynamic columns, we can use Script Task inside a Foreach Loop Container to parse the first row of the flat file to get the columns names and save them into a .NET variable, then, we can create “Create Table” script based on this
    variable, and then store the script into a SSIS package variable. After that, we create a staging table based on the package variable, load the flat file data to the staging table. Eventually, we load data from the staging table to the destination table. For
    the detail steps, please walk through the following blog:
    http://www.citagus.com/citagus/blog/importing-from-flat-file-with-dynamic-columns/ 
    Regards,
    Mike Yin
    TechNet Community Support

  • Can't create log file with java.util.logging

    Hi,
    I have created a class to create a log file with java.util.logging
    This class works correctly as standalone (without jdev/weblogic)
    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.logging.*;
    public class LogDemo
         private static final Logger logger = Logger.getLogger( "Logging" );
         public static void main( String[] args ) throws IOException
             Date date = new Date();
             DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
             String dateStr = dateFormat.format(date);
             String logFileName = dateStr + "SEC" + ".log";
             Handler fh;          
             try
               fh = new FileHandler(logFileName);
               //fh.setFormatter(new XMLFormatter());
               fh.setFormatter(new SimpleFormatter());
               logger.addHandler(fh);
               logger.setLevel(Level.ALL);
               logger.log(Level.INFO, "Initialization log");
               // force a bug
               ((Object)null).toString();
             catch (IOException e)
                  logger.log( Level.WARNING, e.getMessage(), e );
             catch (Exception e)
                  logger.log( Level.WARNING, "Exception", e);
    }But when I use this class...
    import java.io.File;
    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.logging.FileHandler;
    import java.util.logging.Handler;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import java.util.logging.XMLFormatter;
    public class TraceUtils
      public static Logger logger = Logger.getLogger("log");
      public static void initLogger(String ApplicationName) {
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(date);
        String logFileName = dateStr + ApplicationName + ".log";
        Handler fh;
        try
          fh = new FileHandler(logFileName);
          fh.setFormatter(new XMLFormatter());
          logger.addHandler(fh);
          logger.setLevel(Level.ALL);
          logger.log(Level.INFO, "Initialization log");
        catch (IOException e)
          System.out.println(e.getMessage());
    }and I call it in a backingBean, I have the message in console but the log file is not created.
    TraceUtils.initLogger("SEC");why?
    Thanks for your help.

    I have uncommented this line in logging.properties and it works.
    # To also add the FileHandler, use the following line instead.
    handlers= java.util.logging.FileHandler, java.util.logging.ConsoleHandlerBut I have another problem:
    jdev ignore the parameters of the FileHandler method .
    And it creates a general log file with anothers log files created each time I call the method logp.
    So I play with these parameters
    fh = new FileHandler(logFileName,true);
    fh = new FileHandler(logFileName,0,1,true);
    fh = new FileHandler(logFileName,10000000,1,true);without succes.
    I want only one log file, how to do that?

  • Problem unzipping larger files with Java

    When I extract small zip files with java it works fine. If I extract large zip files I get errors. Can anyone help me out please?
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import java.util.zip.*;
    public class  updategrabtest
         public static String filename = "";
         //public static String filesave = "";
        public static boolean DLtest = false, DBtest = false;
         // update
         public static void main(String[] args)
              System.out.println("Downloading small zip");
              download("small.zip"); // a few k
              System.out.println("Extracting small zip");
              extract("small.zip");
              System.out.println("Downloading large zip");
              download("large.zip"); // 1 meg
              System.out.println("Extracting large zip");
              extract("large.zip");
              System.out.println("Finished.");
              // update database
              boolean maindb = false; //database wasnt updated
         // download
         public static void download (String filesave)
              try
                   java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
                   java.net.URL("http://saveourmacs.com/update/" + filesave).openStream());
                   java.io.FileOutputStream fos = new java.io.FileOutputStream(filesave);
                   java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
                   byte data[] = new byte[1024];
                   while(in.read(data,0,1024)>=0)
                        bout.write(data);
                   bout.close();
                   in.close();
              catch (Exception e)
                   System.out.println ("Error writing to file");
                   //System.exit(-1);
         // extract
         public static void extract(String filez)
              filename = filez;
            try
                updategrab list = new updategrab( );
                list.getZipFiles();
            catch (Exception e)
                e.printStackTrace();
         // extract (part 2)
        public static void getZipFiles()
            try
                //String destinationname = ".\\temp\\";
                String destinationname = ".\\";
                byte[] buf = new byte[1024]; //1k
                ZipInputStream zipinputstream = null;
                ZipEntry zipentry;
                zipinputstream = new ZipInputStream(
                    new FileInputStream(filename));
                zipentry = zipinputstream.getNextEntry();
                   while (zipentry != null)
                    //for each entry to be extracted
                    String entryName = zipentry.getName();
                    System.out.println("entryname "+entryName);
                    int n;
                    FileOutputStream fileoutputstream;
                    File newFile = new File(entryName);
                    String directory = newFile.getParent();
                    if(directory == null)
                        if(newFile.isDirectory())
                            break;
                    fileoutputstream = new FileOutputStream(
                       destinationname+entryName);            
                    while ((n = zipinputstream.read(buf, 0, 1024)) > -1)
                        fileoutputstream.write(buf, 0, n);
                    fileoutputstream.close();
                    zipinputstream.closeEntry();
                    zipentry = zipinputstream.getNextEntry();
                }//while
                zipinputstream.close();
            catch (Exception e)
                e.printStackTrace();
    }

    In addition to the other advice, also change every instance of..
    kingryanj wrote:
              catch (Exception e)
                   System.out.println ("Error writing to file");
                   //System.exit(-1);
    ..to..
    catch (Exception e)
    e.printStackTrace();
    }I am a big fan of the stacktrace.

  • Executing a file with Java?

    Hi,
    I wanted to know how I could execute a file with java. Here are a couple scenarios - let's say I am developing an anti-spyware utility and I wanted to first write a batch file, and then create it in a folder, then run it when they click "Run". Then afterwards I want to shutdown their computer.
    My Mindset:
    - FileWriter to create the .bat and write the Batch commands.
    - Execute the batch file.
    - Execute the shutdown.exe file to reboot their PC.
    So my simple question is, how can I execute a file?
    Thanks!
    -Josh

    Well here is the code I have:
                try
                    Runtime.getRuntime().exec("cmd.exe /c test.bat");
                catch(IOException e1)
                    //NOTHING
                }Now my cmd.exe is obviously in my Windows System32 folder, and my "test.bat" file is in my C:\ root directory. So I am wondering why that wont execute. I tried a fer other things too like:
    Runtime.getRuntime().exec("cmd.exe  c:\test.bat");that didn't work either, because you can't have a "\" in a string...
    So how can I get this thing to execute the batch file?

  • Is it possible to play .rm and .wma file with java?

    Hello Friends,
    Please tell me,
    how to play .rm and .wma file with java?
    Thanks,
    Harsh Modha

    As far as I know, you can not play those files.
    Here you have the complete list of supported formats. Hope this helps.
    http://java.sun.com/products/java-media/jmf/2.1.1/formats.html
    Maybe you should try to convert from wma or rm to a supported format before attempting to play it.

  • Problem in printing pdf document with java code

    Hi All
    I want to print a pdf document with java code i have used PDFRenderer.jar to compile my code.
    Code:
    File f = new File("C:/Documents and Settings/123/Desktop/1241422767.pdf");
    FileInputStream fis = new FileInputStream(f);
    FileChannel fc = fis.getChannel();
    ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    PDFFile pdfFile = new PDFFile(bb); // Create PDF Print Page
    PDFPrintPage pages = new PDFPrintPage(pdfFile);
    // Create Print Job
    PrinterJob pjob = PrinterJob.getPrinterJob();
    PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
    pjob.setJobName(f.getName());
    Book book = new Book();
    book.append(pages, pf, pdfFile.getNumPages());
    pjob.setPageable(book);
    // System.out.println(pjob.getPrintService());
    // Send print job to default printer
    pjob.print();
    but when i am running my program i am getting error
    Exception in thread "main" java.awt.print.PrinterException: Invalid name of PrintService.
    Please anybody, knows the solution for this error?
    Thanks In Advance
    Indira

    It seems that either there is no default printer setup or you have too many printers or no printer setup at all. Try running the following code. It should print the list of available print services.
    import java.awt.print.*;
    import javax.print.*;
    public class PrintServiceNames{
         public static void main(String args[]) throws Exception {
              PrintService[] printServices = PrinterJob.lookupPrintServices();
              int i;
              for (i = 0; i < printServices.length; i++) {
                   System.out.println("P: " + printServices);
    }From the list pick one of the print service names and set it explicitly like "printerJob.setPrintService(printServices);" and then try running the program.

  • Run batch files through java code

    Hi All
    I need to run a batch file using java code . I am not getting any error, but also no output. Can someone let me know the problem with my code.The code i am using is
    import java.io.*;
    public class batchtest {
         public static void main(String[] args) {
              Runtime r = Runtime.getRuntime();
         Process p= null;
         String line;
              try{
              p = r.exec("cmd /c testBatch.bat");
              BufferedReader input = new BufferedReader
              (new InputStreamReader(p.getInputStream()));
         while ((line = input.readLine()) != null) {
         System.out.println(line);
         input.close();
              System.out.println("running...");
              }catch(Exception e)
                   e.printStackTrace();
    }

    Maybe this helps:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

Maybe you are looking for