IO File help needed

Hello all,
Here is my situation, I need to create an object, populate the object with data, and then store the object in a linked list. The object is created in a reference class that I created, and the data for the object is being read in from a .txt file. My problem is that I am opening the link to the .txt file from my driver class, but can't seem to get the readLine() to work in the reference class. Here is what I have:
Driver Class:
import java.io.*;
import java.util.LinkedList;
import javax.swing.*;
import BaseballPlayer;
public class BaseballStats
  public static void main(String[] args)
    boolean morePlayers = true;
    BufferedReader in = null;
    try
      LinkedList playerList = new LinkedList();
      in = new BufferedReader( new FileReader( "PlayerStats.txt" ) );
      BaseballPlayer player = new BaseballPlayer();
      while(morePlayers == true)
        player.newPlayer();
        playerList.add(player);
      for (i = 0; i < playerList.size(); i++)
        System.out.println(playerList.get(i));
    catch (Exception e)
      Controller.fatal("BaseballStats.main()", e.toString());
}Reference Class:
import java.io.*;
import java.util.*;
public class BaseballPlayer extends Object
  public boolean newPlayer()
    myName = in.readLine();
    myPosition = in.readLine();
    myAge = in.readLine();
    myBirthdate = in.readLine();
    myAtBats = in.readLine();
    atBats = Double.parseDouble(myAtBats);
    myHits = in.readLine();
    hits = Double.parseDouble(myHits);
    moreData = in.readLine();
    if (moreData != null)
      morePlayers = true;
    else
      morePlayers = false;
    return morePlayers;
  private String myName;
  private String myPosition;
  private String myAge;
  private String myBirthdate;
  private String myAtBats;
  private String myHits;
  private String moreData;
  private boolean morePlayers;
  private double atBats;
  private double hits;
}Text File:
Jose Cuervo
Pitcher
32
July 1, 1970
250
100
The error I get is: Variable in not found in class
Technically I need to read several players into the linked list from one data file, but I'll tackle that problem after i am able to read 1!
Any help would be greatly appreciated

import java.io.*;
import java.util.LinkedList;
import javax.swing.*;
import BaseballPlayer;
public class BaseballStats{ 
  public static void main(String[] args)  {   
    boolean morePlayers = true;   
    BufferedReader in = null;   
    try {
      LinkedList playerList = new LinkedList();     
      in = new BufferedReader(new FileReader("PlayerStats.txt"));     
      BaseballPlayer player = new BaseballPlayer();     
      while(morePlayers == true){ //morePlayers == true,
                                  //Will this loop ever stop??
                                  //when does "morePlayers" become false?
        player.newPlayer(); //player does not have reference to   
                            //BufferedReader instance, u have to pass it
                            //"BufferedReader in" has scope within
                            //main() method only
        playerList.add(player);     
      for (i = 0; i < playerList.size(); i++)       
        System.out.println(playerList.get(i));   
    } catch (Exception e){     
      Controller.fatal("BaseballStats.main()", e.toString());   
}

Similar Messages

  • Burning full resolution jpg files help needed

    Hi there, I am relatively new to Aperture but I have been using iPhoto for years.  I can't seem to find a way to burn photos to my optical drive.  I need them full resolution for printing purposes.  Any help would be most appreciated.  Thanks

    how do I find that window?  *did I just say window?*
    When you export a photo with "File > Export > Version", a File Chooser dialog will open. Set the "Export Preset" pop up to "Edit". That lets you edit the settings for the different JPEG and TIFF export settings:

  • OBIA Environment - Informatica & DAC Setup files - Help Needed

    We want to setup OBIA test environment but worried which files should be downloaded for Informatica(Client and Server) and DAC(Client and Server), here we are confused with file names.
    We already have the Oracle Applications, Target DB and OBIEE in place, could somebody please help us in finding the right files needed for the remaining OBIA setup(i.e. Informatica Client & Server, DAC Client & Server) from the below list
    Note : Our machines have 64bit OS, the below list is from edelivery.oracle.com
    Product Pack : Oracle Business Intelligence
    Platform      : Microsoft Windows x86 (64-bit)
    Oracle Business Intelligence Applications 7.9.6.3 for Microsoft Windows                     V26578-01           519M
    Oracle Business Intelligence Data Warehouse Administration Console 10.1.3.4.1 for Microsoft Windows      V16377-01           181M
    Oracle Business Intelligence Data Warehouse Administration Console 10.1.3.4.1 for Microsoft Windows
    and Informatica PowerCenter and PowerConnect Adapters 9.0.1 for Windows x86 (64-bit) (Part 1 of 2)      V30854-01 Part 1 of 2      2.0G
    Oracle Business Intelligence Data Warehouse Administration Console 10.1.3.4.1 for Microsoft Windows
    and Informatica PowerCenter and PowerConnect Adapters 9.0.1 for Windows x86 (64-bit) (Part 2 of 2)      V30854-01 Part 2 of 2      26M
    Oracle Business Intelligence Applications Licensing and Packaging Guide 7.9.6.3 and Informatica
    PowerCenter and PowerConnect Adapters Client 9.0.1 (Part 1 of 2)                          V30964-01 Part 1 of 2      706M
    Oracle Business Intelligence Applications Licensing and Packaging Guide 7.9.6.3 and Informatica
    PowerCenter and PowerConnect Adapters Client 9.0.1 (Part 2 of 2)                          V30964-01 Part 2 of 2      2.0G
    Oracle Business Intelligence Data Warehouse Administration Console 10.1.3.4.1 for Microsoft Windows
    and Informatica PowerCenter and PowerConnect Adapters 9.1 for Windows x86 (64-bit) (Part 1 of 2)      V30859-01 Part 1 of 2      2.0G
    Oracle Business Intelligence Data Warehouse Administration Console 10.1.3.4.1 for Microsoft Windows
    and Informatica PowerCenter and PowerConnect Adapters 9.1 for Windows x86 (64-bit) (Part 2 of 2)      V30859-01 Part 2 of 2      1.4G
    Oracle Business Intelligence Applications Licensing and Packaging Guide 7.9.6.3 and Informatica
    PowerCenter and PowerConnect Adapters Client 9.1 (Part 1 of 2)                               V33700-01 Part 1 of 2      1.7G
    Oracle Business Intelligence Applications Licensing and Packaging Guide 7.9.6.3 and Informatica
    PowerCenter and PowerConnect Adapters Client 9.1 (Part 2 of 2)                               V33700-01 Part 2 of 2      2.0G
    Thanks,
    Sumanth

    Hi Sumanth,
    The below are the software packages, download them and install. Do let me know if you have any config issues.
    BI Apps:
    Oracle Business Intelligence Applications 7.9.6.3 for Microsoft Windows V26578-01 519M
    DAC:
    Oracle Business Intelligence Data Warehouse Administration Console 10.1.3.4.1 for Microsoft Windows V16377-01 181M
    Informatica Server:
    Oracle Business Intelligence Data Warehouse Administration Console 10.1.3.4.1 for Microsoft Windows
    and Informatica PowerCenter and PowerConnect Adapters 9.0.1 for Windows x86 (64-bit) (Part 1 of 2) V30854-01 Part 1 of 2 2.0G
    Oracle Business Intelligence Data Warehouse Administration Console 10.1.3.4.1 for Microsoft Windows
    and Informatica PowerCenter and PowerConnect Adapters 9.0.1 for Windows x86 (64-bit) (Part 2 of 2) V30854-01 Part 2 of 2 26M
    Informatica Client:
    Oracle Business Intelligence Data Warehouse Administration Console 10.1.3.4.1 for Microsoft Windows
    and Informatica PowerCenter and PowerConnect Adapters 9.1 for Windows x86 (64-bit) (Part 1 of 2) V30859-01 Part 1 of 2 2.0G
    Oracle Business Intelligence Data Warehouse Administration Console 10.1.3.4.1 for Microsoft Windows
    and Informatica PowerCenter and PowerConnect Adapters 9.1 for Windows x86 (64-bit) (Part 2 of 2) V30859-01 Part 2 of 2 1.4G
    Hope this helps. Pls mark correct or helpful
    Thanks,
    SVee

  • Cs4 Mac : linking to open external .app files, help needed!

    I have completed a CDROM for pc users for a client.
    The CDROM contains 15 quizzes in exe format.
    A 'portal' file links to each of these quizzes, so the user returns, having opened and completed the (.exe) quiz file, to the portal and takes another quiz.
    the code to open these 15 quiz files
    on(release){
    fscommand("exec","openexe15a.bat")
    This opens the bat file, which opens the exe
    ----- This works fine
    However, my client wants a mac version,
    I cant find a way to link to the macintosh projector file within the portal file.
    fscomand doesnt work, geturl doesnt work.. any help really would be appreciated.

    I don’t know how .Mac Backup works, so all I can say is which are the files & folders you need to restore from the backup (assuming you did actually back up them, that is).
    Mail stores most preferences and all account settings in ~/Library/Preferences/com.apple.mail.plist (except the passwords, which are stored in the keychain). Everything else, including all your messages and mailboxes, is stored in ~/Library/Mail/.
    Similarly, Address Book (whose data you should back up as well) stores the settings in ~/Library/Preferences/com.apple.AddressBook.plist and the data in ~/Library/Application Support/AddresBook/.
    Other applications store preferences and data in other places. You may want to ask in the appropriate forums for more information on those.
    You may also want to read this:
    How to back up and restore your important Mac OS X 10.4 files
    Note: For those not familiarized with the ~/ notation, it refers to the user's home folder, i.e. ~/Library is the Library folder within the user's home folder.

  • Error not alloving sign my jar file - help needed

    hi guys i am getting the following error while trying to sign the jar file.
    unable to sign the jar ; jar.util.zip.zip exception: invalid entry compressed size .
    i got this while signing the msbase and msutil of MS jdbc jar files.
    what am i suppose to do.
    I am unable to understand one more thing. Do i need to have both jdbcodbc.dll library and msbase,msutil, mssqlserver jar files to connect using jdbc or its ok if i only have the jar files. I would appreciate if somebody can help me in this regard.
    thanks,
    ravi.

    hi guys i got the problem solved i unzipped the files and zipped them agian. Its working well .
    thanks,
    ravi.

  • Restoring Memos from a backup file - Help needed

    I lost my memos in a crash and need to restore them from a backup file.  The Blackberry Desktop Software has the Memos "Dimmed" and the software says "Dimmed entries are read-only data types and cannot be restored".  This makes zero sense.
    Bold 9650
    OS 6.0.0.719
    Any help is appreciated.

    Hi and Welcome to the Community!
    Here is a KB that discusses that error:
    KB04461 Unable to backup or restore some databases to a BlackBerry smartphone using BlackBerry Desktop Software
    Hopefully it contains something useful! There also are multiple existing threads on this site that discuss that exact error...your review of those might prove useful, and a search of this site, using the error message, error code, or symptom, should reveal all applicable existing threads to you.
    Good luck and let us know!
    Occam's Razor nearly always applies when troubleshooting technology issues!
    If anyone has been helpful to you, please show your appreciation by clicking the button inside of their post. Please click here and read, along with the threads to which it links, for helpful information to guide you as you proceed. I always recommend that you treat your BlackBerry like any other computing device, including using a regular backup schedule...click here for an article with instructions.
    Join our BBM Channels
    BSCF General Channel
    PIN: C0001B7B4   Display/Scan Bar Code
    Knowledge Base Updates
    PIN: C0005A9AA   Display/Scan Bar Code

  • .MTS Audio Files help needed

    I'm having a little trouble with editing.
    The footage I am editing are .MTS files. Both the audio and video.
    The video is playing fine (well, as best it can for my rubbish uni computers) but I am having trouble hearing the audio - and I'm getting lots of conforming errors.
    I read here that CS4 doesn't support .MTS audio files. If that's the case then why can I hear some of them and not the others?
    Should I be converting the audio into another format before editing? If so, then what's the best format to convert to, and how can I do it in a way that I don't have to strip the audio from the video (I want to keep them perfectly synced)
    Thanks in advance for your help,
    Nath

    Hi Bill,
    Thanks for your reply, that's an interesting article. The files I am editing are stored on an external hard drive - I tried deleting a few files on there to make some room (whilst I was in the editing suite) and it wouldn't let me delete them because it said I didn't have administrator permission - despite this being my own hard drive. Could that be causing a problem with conforming? Should I copy the files accross onto the internal drive? The scratch disks are set to the local D drive.
    Nath
    Ps: I've just downloaded a program which is converting the .MTS files into .MOV. I don't really want to do this as this will probably loose quality - but I'm trying everything! What would be the optimum file type to convert to?

  • Re: Site definition file help needed.

    On Fri, 22 Dec 2006 09:38:17 -0800, Kevin D-R
    <[email protected]> wrote:
    >Which brings me to Dreamweaver. I have copied everything
    over and
    >reinstalled Dreamweaver, but my site definition
    information is gone.
    >
    >Any ideas on how to get that copied over?
    The site definition is stored in the Windows system registry.
    If you
    cannot boot from the old hard drive, you may need to re-enter
    the site
    information.
    Gary

    Thanks so much for your response Anita.
    Since I posted this, I noticed a blurb on the Weblogic site that mentioned Service
    Pack 9 fixes any problems with JSSE and SSL from within a Weblogic jsp/servlet.
    That service pack also includes an example of using the Weblogic SSL routines
    to make outgoing HTTPS connections. So, I'm trying to install service pack 9 and
    use the example code included in the distribution. I may end up trying what you
    listed below however, because SP 9 seems to be screwing up some of our functionality.
    <sigh> It nevers ends....
    "Anita" <[email protected]> wrote:
    >
    1) Put the JSSE classes in the lib/ext directory.
    2) in the Weblogic.properties file change the weblogic.security.SSLHandler.enable=true
    to weblogic.security.SSLHandler.enable=false
    3) in the weblogic.policy file under a 'grant' directive for all code
    bases,
    put permission java.util.PropertyPermission "java.protocol.handler.pkgs",
    "write";

  • Password protected Files help needed Urgent

    I have a close family friend who's husband has just passed away, I’ve been helping her gain access to her husband’s laptop ect, he was the accountant for the family business, He used Star office version 8, the problem we have is many of his files are password protected.
    I have 2 questions
    1) How many attempts can the wife have to try and guess the password before she's locked out of the file?
    2) Is there any way to hack/bypass these passwords? (3rd party software, a company ect ect)
    I would really appreciate your help as the family's bank manager is visiting on Wednesday to go over the health of the business and many of these important financial files are locked.
    Thanks in advance
    Darren

    But it did work on windows vista with reader 7. If it is not at all possible then
    my question is can I uninstall reader 9 and install reader 7.
    will it work on windows 7 64 bit

  • Downloading a file help needed - Urgent

    Can anyone let me know how do i download a file that resides in database(BLOB format) in different box(server) to the local client's machine without prompting for any of the download dialog box using java. Also after downloading the correct application should be launched to view the downloaded file.
    thanks in advance
    regds
    chandru.

    Hi kev,
    Even I have done the same thing using servlets. But, My question is,
    When i click the download button from my application. The file should be downloaded to a pre-defined directory in clients machine and then the approperiate application should be launched to view the file.All this operation should take place just at the click of download button. Is this possible?.
    thanks
    chandru
    I've done this using a servlet. Assuming that the
    user's browser has the correct plugin available then
    you can call res.setContentType() and set the
    mime-type of the file, then you can call
    res.getOutputStream and stream the value from the
    database (using the relevent getXxxStream method of
    the BLOB) directly to the output. If for example your
    content type is application/ms-word, then the word
    plugin will be loaded and the file will be displayed.
    If your problem is with Database access and not with
    the display of the file, you'll have to let us know.
    Hope this helps
    Kev ([email protected])

  • CS3 WONT ACCEPT MP3 FILES - HELP NEEDED.

    Does anyone know why I cant add Mp3 files to PP, when I try adding one it says "File Format not supported", this never happened with PP 2.0.

    >got it from a friend
    Was it on an Adobe DVD... or a DVD-R your friend wrote?
    Did your friend certify that he never installed it so you CAN activate?
    What does Help--About show?

  • Manifest file: Help needed

    Hi everyone,
    We have a java app that includes in its install package some JRE components.
    We use to put these JREs under jre a subdirectory of the App main DIR at this point everything works fine and the manifest file looks like:
    Manifest-Version: 1.0
    Main-Class: mycompany.DIR1.MAINCLASSNAME
    Class-Path: .\jre\lib\jh.jar
    Created-By: 1.2.2 (Sun Microsystems Inc.)
    The problem with this approach is when you install more than one copy you will duplicate also the JRE components (some 15 Megs).
    To avoid these duplications we decided to put the JREs in a common directory such as <WINDIR> (WINNT / Windows)
    to do so the manifest file has to be updated to reflect the jh.jar path.
    I tried a hard coded path: Class-Path: e:\WINNT\jre\lib\jh.jar and got this error:
    Exception in thread "main" java.lang.NoClassDefFoundError: mycompany/DIR1/MAINCLASSNAME
    by removing the class-path line I got the following error:
    Exception in thread "main" java.lang.NoClassDefFoundError: javax/help/HelpSetException at mycompany.DIR1.MAINCLASSNAME.main(MAINCLASSNAME.java:30)
    Please help,
    any idea or suggestions are appreciated.
    Thanks,
    dobject.

    You could try a CLASSPATH along the lines of e:\WINNT\jre\lib\jh.jar;.
    Note, though, that you're throwing a lot of portability away.

  • Help needed  while exporting crystal reports to HTML file format using java

    Help needed  while exporting crystal reports to HTML file format using java api(not using crystalviewer).i want to download the
    html file of the report
    thanks

    the ReportExportFormat class does not have HTML format, it has got to be XML. Export to HTML is available from CR Designer only.
    Edited by: Aasavari Bhave on Jan 24, 2012 11:37 AM

  • Urgent help needed - new to Macs, accidently cut and paste over top of photo folder and now no sign of folder or file, no auto back-up in place, how can I restore photos pls

    Urgent help needed - new to Macs, accidently cut and paste over top of photo folder and now no sign of folder or file, no auto back-up in place, how can I restore photos pls

    Thanks for prompt reply, yes we have tried that but have now closed down the browser we where the photos were.
    We haven't sent up time machine, do you know whether there is any roll-back function on a Mac?
    Thanks

  • Help needed:Printing HTML file using javax.print

    Hi
    I am using the following code which i got form the forum for rpinting an HTML file.
    The folllowing code is working fine, but the problem is the content of HTML file is not getting printed. I am geeting a blank page with no content. What is the change that is required in the code? ALso is there any simpler way to implement this. Help needed ASAP.
    public boolean printHTMLFile(String filename) {
              try {
                   JEditorPane editorPane = new JEditorPane();
                   editorPane.setEditorKit(new HTMLEditorKit());
                   //editorPane.setContentType("text/html");
                   editorPane.setSize(500,500);
                   String text = getFileContents(filename);
                   if (text != null) {
                        editorPane.setText(text);                    
                   } else {
                        return false;
                   printEditorPane(editorPane);
                   return true;
              } catch (Exception tce) {
                   tce.printStackTrace();
              return false;
         public String getFileContents(String filename) {
              try {
                   File file = new File(filename);
                   BufferedReader br = new BufferedReader(new FileReader(file));
                   String line;
                   StringBuffer sb = new StringBuffer();
                   while ((line = br.readLine()) != null) {
                        sb.append(line);
                   br.close();
                   return sb.toString();
              } catch (Exception tce) {
                   tce.printStackTrace();
              return null;
         public void printEditorPane(JEditorPane editorPane) {
                   try {
                        HTMLPrinter htmlPrinter = new HTMLPrinter();
                        htmlPrinter.printJEditorPane(editorPane, htmlPrinter.showPrintDialog());
                   } catch (Exception tce) {
                        tce.printStackTrace();
         * Sets up to easily print HTML documents. It is not necessary to call any of the setter
         * methods as they all have default values, they are provided should you wish to change
         * any of the default values.
         public class HTMLPrinter {
         public int DEFAULT_DPI = 72;
         public float DEFAULT_PAGE_WIDTH_INCH = 8.5f;
         public float DEFAULT_PAGE_HEIGHT_INCH = 11f;
         int x = 100;
         int y = 80;
         GraphicsConfiguration gc;
         PrintService[] services;
         PrintService defaultService;
         DocFlavor flavor;
         PrintRequestAttributeSet attributes;
         Vector pjlListeners = new Vector();
         Vector pjalListeners = new Vector();
         Vector psalListeners = new Vector();
         public HTMLPrinter() {
              gc = null;
              attributes = new HashPrintRequestAttributeSet();
              flavor = null;
              defaultService = PrintServiceLookup.lookupDefaultPrintService();
              services = PrintServiceLookup.lookupPrintServices(flavor, attributes);
              // do something with the supported docflavors
              DocFlavor[] df = defaultService.getSupportedDocFlavors();
              for (int i = 0; i < df.length; i++)
              System.out.println(df.getMimeType() + " " + df[i].getRepresentationClassName());
              // if there is a default service, but no other services
              if (defaultService != null && (services == null || services.length == 0)) {
              services = new PrintService[1];
              services[0] = defaultService;
         * Set the GraphicsConfiguration to display the print dialog on.
         * @param gc a GraphicsConfiguration object
         public void setGraphicsConfiguration(GraphicsConfiguration gc) {
              this.gc = gc;
         public void setServices(PrintService[] services) {
              this.services = services;
         public void setDefaultService(PrintService service) {
              this.defaultService = service;
         public void setDocFlavor(DocFlavor flavor) {
              this.flavor = flavor;
         public void setPrintRequestAttributes(PrintRequestAttributeSet attributes) {
              this.attributes = attributes;
         public void setPrintDialogLocation(int x, int y) {
              this.x = x;
              this.y = y;
         public void addPrintJobListener(PrintJobListener pjl) {
              pjlListeners.addElement(pjl);
         public void removePrintJobListener(PrintJobListener pjl) {
              pjlListeners.removeElement(pjl);
         public void addPrintServiceAttributeListener(PrintServiceAttributeListener psal) {
              psalListeners.addElement(psal);
         public void removePrintServiceAttributeListener(PrintServiceAttributeListener psal) {
              psalListeners.removeElement(psal);
         public boolean printJEditorPane(JEditorPane jep, PrintService ps) {
                   if (ps == null || jep == null) {
                        System.out.println("printJEditorPane: jep or ps is NULL, aborting...");
                        return false;
                   // get the root view of the preview pane
                   View rv = jep.getUI().getRootView(jep);
                   // get the size of the view (hopefully the total size of the page to be printed
                   int x = (int) rv.getPreferredSpan(View.X_AXIS);
                   int y = (int) rv.getPreferredSpan(View.Y_AXIS);
                   // find out if the print has been set to colour mode
                   DocPrintJob dpj = ps.createPrintJob();
                   PrintJobAttributeSet pjas = dpj.getAttributes();
                   // get the DPI and printable area of the page. use default values if not available
                   // use this to get the maximum number of pixels on the vertical axis
                   PrinterResolution pr = (PrinterResolution) pjas.get(PrinterResolution.class);
                   int dpi;
                   float pageX, pageY;
                   if (pr != null)
                        dpi = pr.getFeedResolution(PrinterResolution.DPI);
                   else
                        dpi = DEFAULT_DPI;
                   MediaPrintableArea mpa = (MediaPrintableArea) pjas.get(MediaPrintableArea.class);
                   if (mpa != null) {
                        pageX = mpa.getX(MediaPrintableArea.INCH);
                        pageY = mpa.getX(MediaPrintableArea.INCH);
                   } else {
                        pageX = DEFAULT_PAGE_WIDTH_INCH;
                        pageY = DEFAULT_PAGE_HEIGHT_INCH;
                   int pixelsPerPageY = (int) (dpi * pageY);
                   int pixelsPerPageX = (int) (dpi * pageX);
                   int minY = Math.max(pixelsPerPageY, y);
                   // make colour true if the user has selected colour, and the PrintService can support colour
                   boolean colour = pjas.containsValue(Chromaticity.COLOR);
                   colour = colour & (ps.getAttribute(ColorSupported.class) == ColorSupported.SUPPORTED);
                   // create a BufferedImage to draw on
                   int imgMode;
                   if (colour)
                        imgMode = BufferedImage.TYPE_3BYTE_BGR;
                   else
                        imgMode = BufferedImage.TYPE_BYTE_GRAY;
                   BufferedImage img = new BufferedImage(pixelsPerPageX, minY, imgMode);
                   Graphics myGraphics = img.getGraphics();
                   myGraphics.setClip(0, 0, pixelsPerPageX, minY);
                   myGraphics.setColor(Color.WHITE);
                   myGraphics.fillRect(0, 0, pixelsPerPageX, minY);
                        java.awt.Rectangle rectangle=new java.awt.Rectangle(0,0,pixelsPerPageX, minY);
                   // call rootView.paint( myGraphics, rect ) to paint the whole image on myGraphics
                   rv.paint(myGraphics, rectangle);
                   try {
                        // write the image as a JPEG to the ByteArray so it can be printed
                        Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
                        ImageWriter writer = (ImageWriter) writers.next();
                                       // mod: Added the iwparam to create the highest quality image possible
                        ImageWriteParam iwparam = writer.getDefaultWriteParam();
                        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
                        iwparam.setCompressionQuality(1.0f); // highest quality
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        ImageOutputStream ios = ImageIO.createImageOutputStream(out);
                        writer.setOutput(ios);
                        // get the number of pages we need to print this image
                        int imageHeight = img.getHeight();
                        int numberOfPages = (int) Math.ceil(minY / (double) pixelsPerPageY);
                        // print each page
                        for (int i = 0; i < numberOfPages; i++) {
                             int startY = i * pixelsPerPageY;
                             // get a subimage which is exactly the size of one page
                             BufferedImage subImg = img.getSubimage(0, startY, pixelsPerPageX, Math.min(y - startY, pixelsPerPageY));
                                                 // mod: different .write() method to use the iwparam parameter with highest quality compression
                             writer.write(null, new IIOImage(subImg, null, null), iwparam);
                             SimpleDoc sd = new SimpleDoc(out.toByteArray(), DocFlavor.BYTE_ARRAY.JPEG, null);
                             printDocument(sd, ps);
                             // reset the ByteArray so we can start the next page
                             out.reset();
                   } catch (PrintException e) {
                        System.out.println("Error printing document.");
                        e.printStackTrace();
                        return false;
                   } catch (IOException e) {
                        System.out.println("Error creating ImageOutputStream or writing to it.");
                        e.printStackTrace();
                        return false;
                   // uncomment this code and comment out the 'try-catch' block above
                   // to print to a JFrame instead of to the printer
                   /*          JFrame jf = new JFrame();
                             PaintableJPanel jp = new PaintableJPanel();
                             jp.setImage( img );
                             JScrollPane jsp = new JScrollPane( jp );
                             jf.getContentPane().add( jsp );
                             Insets i = jf.getInsets();
                             jf.setBounds( 0, 0, newX, y );
                             jf.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
                             jf.setVisible( true );*/
                   return true;
              * Print the document to the specified PrintService.
              * This method cannot tell if the printing was successful. You must register
              * a PrintJobListener
              * @return false if no PrintService is selected in the dialog, true otherwise
              public boolean printDocument(Doc doc, PrintService ps) throws PrintException {
                   if (ps == null)
                   return false;
                   addAllPrintServiceAttributeListeners(ps);
                   DocPrintJob dpj = ps.createPrintJob();
                   addAllPrintJobListeners(dpj);
                   dpj.print(doc, attributes);
                   return true;
              public PrintService showPrintDialog() {
                   return ServiceUI.printDialog(gc, x, y, services, defaultService, flavor, attributes);
              private void addAllPrintServiceAttributeListeners(PrintService ps) {
                   // add all listeners that are currently added to this object
                   for (int i = 0; i < psalListeners.size(); i++) {
                   PrintServiceAttributeListener p = (PrintServiceAttributeListener) psalListeners.get(i);
                   ps.addPrintServiceAttributeListener(p);
              private void addAllPrintJobListeners(DocPrintJob dpj) {
                   // add all listeners that are currently added to this object
                   for (int i = 0; i < pjlListeners.size(); i++) {
                   PrintJobListener p = (PrintJobListener) pjlListeners.get(i);
                   dpj.addPrintJobListener(p);
              // uncomment this also to print to a JFrame instead of a printer
              /* protected class PaintableJPanel extends JPanel {
                   Image img;
                   protected PaintableJPanel() {
                        super();
                   public void setImage( Image i ) {
                        img = i;
                   public void paint( Graphics g ) {
                        g.drawImage( img, 0, 0, this );
    Thanks
    Ram

    Ram,
    I have had printing problems too a year and a half ago. I used all printing apis of java and I still find that it is something java lacks. Now basically you can try autosense. To check whether your printer is capable of printing the docflavor use this PrintServiceLookup.lookupPrintServices(flavor, aset); . If it lists the printer then he can print the document otherwise he can't. I guess that is why you get the error.
    Regards,
    Kevin

Maybe you are looking for