GetClass().getResourceAsStream()

Hi guys, I have a similar problem from several days and I thing it is of the same nature. Here it is:
I create a very simple JSP that uses the Connection Manager package and tries to get the info for the connections (described in connections.xml). This code works on tomcat, but not on OC4J. The exception is that the system cannot find the resource property file. After looking in the source of the connection manager's class DefaultConnectionStore, I found the reason in method read(). The code getClass().getResourceAsStream(fName) doesn't want to find the file. However the connecions.xml is exactly where it has to be.
I was looking for a solution in configuring the OC4J/directories/paths - nothing. The only thing that worked was to modify the DefaultConnectionStore and load the file as a normal input stream instead of getting it by the class/classloader routines.
Why is that?
10x

Hi guys, I have a similar problem from several days and I thing it is of the same nature. Here it is:
I create a very simple JSP that uses the Connection Manager package and tries to get the info for the connections (described in connections.xml). This code works on tomcat, but not on OC4J. The exception is that the system cannot find the resource property file. After looking in the source of the connection manager's class DefaultConnectionStore, I found the reason in method read(). The code getClass().getResourceAsStream(fName) doesn't want to find the file. However the connecions.xml is exactly where it has to be.
I was looking for a solution in configuring the OC4J/directories/paths - nothing. The only thing that worked was to modify the DefaultConnectionStore and load the file as a normal input stream instead of getting it by the class/classloader routines.The classloader which jdev-cm.jar is loaded with can not load from the WAR, you must use:
Thread.currentThread().getContextClassLoader().getResourceAsStream( fName );
We'll have this fixed in the next maintenance release of JDeveloper.
Hope this helps,
Rob

Similar Messages

  • Maximum size of a file that  the getResourceAsStream() can read?

    hi guys.before i post this new topic, i have search through the forum,and google. on the web .so reply are appreciated.
    1) getResourceAsStream() method, is there a way to know the maximum size of a file that the getResourceAsStream() can read?
    InputStream          is = getClass().getResourceAsStream("Dream2.gif");
                                  byte[]               byte0          = new byte[10 * 1024];
    bcos the size of my bytearray is hardcoded, if any thing is greater than that size ,my program would crash.so i would like to know if there is a way to do that
    2)if that is not available, are there any methods in j2me using any connection (http or socket),that can know the maximum size of the file that are available??????

    You won't be able to tell how big the resource is using this approach. However, since your resource is in the JAR you will be able to know the size of it before hand.
    Otherwise, use the read(byte[], int, int) method to read the resource in chunks like this:
    int count = 0;
    byte[] bytes = new byte[1024];
    while ((count = read(bytes, count, 1024)) != -1) {
      // do something like write to a ByteArrayOutputStream
    }Although redundant, using this approach you can see that you can keep a count of the number of bytes you've read and thus know the total size of the resource.

  • GetResourceAsStream(String name)  - how to use it?

    I tryed to read from a "res.txt" file some text data. This is a test app:
    public class ResTest extends MIDlet{
         public void startApp(){
              try{
                   InputStream is=new String().getClass().getResourceAsStream("/res.txt");
                   DataInputStream dis=new DataInputStream(is);
                   System.out.println(dis.readUTF());
              }catch(Exception e){System.out.println(e);}     
         public void destroyApp(boolean bool){}
         public void pauseApp(){}
    All I got was EOFException.
    So I tryed a different way to read data usinf a loop:
                   char ch;
                   while((ch=dis.readChar())!=-1){
                   System.out.print(ch);
    And than I got:
    ??????java.io.EOFException
    The data in "res.txt" file (I put this file to "res" direction of my project, I use KToolbar):
    Jajko
    Banan

    I'm guessing that the res.txt file is a basic ASCII file, right?
    If this is the case then that is your problem. When you used readUTF() the implementation was expecting a string in UTF format and not basic ASCII so it didn't know how to read it.
    And when you used the readChar() method you have to remember that Java is a Unicode language so chars are 2 bytes. If the string has an odd number of characters then the last character won't have the 2 bytes and you will get an EOFException. And even if the number of chars was even, you wouldn't get the exception but the text wouldn't be what you expect since it was reading text encoded in single byte ASCII format.
    You have two choices:
    a) Encode the res.txt file appropiately, either save as as a UTF-8 file and use readUTF(), or a Unicode file and use the readChar() method.
    b) Use readByte() instead of readChar() and save the bytes in an array, then pass that array to a string constructor.
    shmoove

  • Problem with getResourceAsStream

    Hi,
    I ran into a problem with using getResourceAsStream. My application is packaged in an ear-file and consists of a WAR an EJB-JAR and multiple utility JARs. Everything deploys fine and I don't have any classloading problems, so the class-path settings in the MANIFEST-MF files seem to be fine.
    The problem starts when a stateless session bean tries to configure a part of the application by calling getResourceAsStream to retrieve the configuration xml file which is packaged in the same JAR file like the class which is calling getResourceAsStream. In every other app server I used so far, that's working perfectly fine. The JAR is even displayed in the list of the class loader and as I said, i can load classes from that JAR. But every time I try to load a resource file from that JAR, it fails. If I call getResource to get a URL object that works and gives me the URL to the desired file, but a load of that fails though.
    If I package the file into the WAR or the EJB-JAR getResourceAsStream will find it and hand it back.
    I'm absolutely puzzeled by this behavior and would greatly appretiate any hints to be able to read this resource file.
    Thanks...
    Andreas

    Let me try to answer both questions -- and thanks for all the help. The class is wihin a package and let me explain further...
    1) I'm testing outside the netbeans IDE by executing:
    java -jar MyJar.jar
    This works fine when I had the old version of the code:
    iStream = this.getClass().getResourceAsStream(strategyFile);
    However, then I have the previously noted problem of trying to run tests within the netbeans ide and not being able to find the test files unless they are included in the source package (non-test version).
    2) If I switch the code as suggested to:
    iStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(strategyFile);
    Then the netbeans Junit tests function and can read the test files from the test package within the netbeans IDE when I execute the Junit tests. However, when I go outside the IDE and try
    java -jar MyJar.jar
    the default file is not found in the jar. I've checked the jar file and verified that data file is inside the jar via jar tf.

  • GetResourceAsStream problem in a EJB JAR

    Hello,
    I am trying to get a xml file from the same JAR file my EJB's are
    bundled in on 6.1. Its not in the WAR file but the EJB jar file.
    I've been trying to use:
    getClass().getClassLoader().getResourceAsStream("www.xml")
    and various different versions of this (using "/www.xml')
    I've tried placing the xml file in the root of the JAR file and in the
    same package as the class. I get the impression that its always
    looking in the weblogic class path, and not the classloaders. (it
    works if I place the file in the Weblogic6.1 dir)
    Has anyone managed to retrieve file resources from their EJB JAR
    files? If so how?
    Thanks

    I do this by placing the resource file in it's own .jar file. Then place that .jar file in the .ear file with
    the ejb .jar files. Then put the resource .jar file in the classpath using the Class-Path: manifest directive
    in the ejb .jar files. Then you can use this.getClass().getResourceAsStream("/foo.xml") in the ejb bean
    class.
    I've never tried it by placing the resource file in the ejb .jar file. I would think it would work, but
    apparently not?
    Bill Kemp
    BEA
    Wayne wrote:
    Actually I tried this and it doesn't seem to work. I imagine its
    becuase the EJB classloader can't see the resources in the WAR file?
    Remember I'm trying to load the resource from an EJB JAR file not a
    WAR file.
    Any idea's how I could do this?
    thanks
    Rajesh Mirchandani <[email protected]> wrote in message news:<[email protected]>...
    If the file is in WEB-INF/classes within your WAR it should work if you
    execute
    this.getClass().getClassLoader().getResourceAsStream("www.xml");
    Wayne wrote:
    Hello,
    I am trying to get a xml file from the same JAR file my EJB's are
    bundled in on 6.1. Its not in the WAR file but the EJB jar file.
    I've been trying to use:
    getClass().getClassLoader().getResourceAsStream("www.xml")
    and various different versions of this (using "/www.xml')
    I've tried placing the xml file in the root of the JAR file and in the
    same package as the class. I get the impression that its always
    looking in the weblogic class path, and not the classloaders. (it
    works if I place the file in the Weblogic6.1 dir)
    Has anyone managed to retrieve file resources from their EJB JAR
    files? If so how?
    Thanks

  • GetResourceAsStream and Weblogic 6

    Hi all,
    I'm interested in loading some error messages from a file in Weblogic 6,
    and caching the result. One thing I note about this brave new world of
    EAR packaging is that there's really nowhere to put extra files of your
    own choosing.
    So I figured what I could do was use getResourceAsStream() and therefore
    have the classloader search the classpath for my files full of messages.
    So I've tried bundling the file in the top level of one of my EAR
    archives, or at the top of one of my EJB jars, and doing
    getClass().getResourceAsStream("user_error_messages.xml");
    and
    getClass().getResourceAsStream("/user_error_messages.xml");
    but no dice :(
    I also tried making a resources.jar, which contains only this XML file,
    and placing this in
    web-inf/lib/resources.jar in my WAR file, but no dice there either.
    Does J2EE packaging (EAR/WAR) render getResourceAsStream unusable on
    Weblogic 6?
    Anyone having any luck with a packing scheme that works?
    AndyT

    Hi,
    I have the same problem that I have to put the properties file in the same
    directory with the class that loads it. However, I want to change the
    settings when I deploy. If I put the file in EJB jar, I have to rebuild the
    jar everytime I make a change. Is there any better way doing this? With
    weblogic 4.5.1, we put all property files under separate directory named
    /properties/propertyFile.properties. When we make a change to a property
    file, we just need to bound weblogic and it will load the change. This
    doesn't work with weblogic 6.0. Any ideas why?
    Thank you very much in advance.
    Vincent
    "Cameron Purdy" <[email protected]> wrote in message
    news:3b3a323d$[email protected]..
    Put it in the EJB jar. If it is in the same package as x.class, use
    x.class.getResource...
    Peace,
    Cameron Purdy
    Tangosol, Inc.
    http://www.tangosol.com
    Tangosol Server: Enabling enterprise application customization
    "Andrew Thompson" <[email protected]> wrote in message
    news:[email protected]..
    Hi all,
    I'm interested in loading some error messages from a file in Weblogic 6,
    and caching the result. One thing I note about this brave new world of
    EAR packaging is that there's really nowhere to put extra files of your
    own choosing.
    So I figured what I could do was use getResourceAsStream() and therefore
    have the classloader search the classpath for my files full of messages.
    So I've tried bundling the file in the top level of one of my EAR
    archives, or at the top of one of my EJB jars, and doing
    getClass().getResourceAsStream("user_error_messages.xml");
    and
    getClass().getResourceAsStream("/user_error_messages.xml");
    but no dice :(
    I also tried making a resources.jar, which contains only this XML file,
    and placing this in
    web-inf/lib/resources.jar in my WAR file, but no dice there either.
    Does J2EE packaging (EAR/WAR) render getResourceAsStream unusable on
    Weblogic 6?
    Anyone having any luck with a packing scheme that works?
    AndyT

  • GetClass() and Output Streams

    I'm trying to save user preferences to a .Properties file, but I can't seem to correctly find the file when I give a relative path. I had no problem loading the file using:
    InputStream inStream = getClass().getResourceAsStream(filename);
    try {
        load(inStream);
    catch (IOException e) {
        System.out.println(e);
    }The .getResourceAsStream(String) returned an InputStream, so that part was easy. I'm trying to find out if there is something similar to this method that returns an OutputStream or if there is a way to resolve the path to an InputStream to use in the construction of an OutputStream. Thank you for any information you can provide.

    getResource() returns a URL...

  • GetResourceAsStream() stops working when run online!

    I have written an applet that I am hosting on a geocities website. The applet
    runs fine in NetBeans, and locally fram an html file, but when I try to run the
    applet online, the:
    BufferedReader in= new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("One.txt")));(it used to be "this.getClass().getResourceAsStream()", but after many
    forum searches and revisions the above version still works in NetBeans
    but not online)
    line throws a NullPointerException because it cant find the file.
    When I disable this line of code, the applet shows up just fine,
    but has no functionality because it draws graphs of the information
    found in the text file I am trying to read.
    Everything is in the same directory, is this a problem with file permissions?
    Or is it a problem with how getResourceAsStream() looks for files?

    I am not using a jar at the moment, I was messing with that earlier and
    was more complicated than it needed to be, I have all of the class files
    for my buttons and such as well as the main applet class "Grapher.class"
    and the class that reads the text file "GetStuff.class" in the main directory of
    my geocities page, "www.geocities.com/bbubenheim/" and the applet tag in
    the html is:
    <applet code="Graph.class" height="600" width="1000">
    </applet>since everything is in the main directory and not jarred then there should be
    no need for an "archive" or "codebase" part.
    Should I try hosting it somewhere else? Or am I missing something?

  • Calling getResourceAsStream to locate property files

    I'm attempting to create a link between Oracle and an external application using an API provided by the vendor.
    This APi has a number of settings that I'd rather keep as properties so I don't have to compile custom code for dev / test / prod.
    I'm attempting to use the getResourceAsStream function locate the prop file. It works fine as a stand alone - but when I run it out of OJVM - can't locate the prop file.
    Load Java shows the prop file in my user_objects list - I just can't seem to get OJVM to let my code know where it is.
    Here's part of the constructor of the class doing the heavy lifting:
    Properties settings = new Properties(default);
    try {
    InputStream sf = this.getClass().getResourceAsStream("ll_util.properties");
    settings.load(sf);
    Any help appreciated!

    Hi Guys,
    I am trying to connect to mysql/oracle database using property file "jdbc.properties" to provide information like driver, url, user name, password etc
    When i put this file within the same package ( com.db in this case ) : I can successfully connect to the database ,
    But when I put this file somewhere else say C:\resources\jdbc.properties I could not locate the property file
    I am using following line of code
    When property file withing the same directory as Class
    InputStream in = QueryTest.class.getResourceAsStream("jdbc.properties");
    Works
    So what's your problem?
    But
    When property file is at C:/resources/ folder
    Why would you want to put it here?
    InputStream in = QueryTest.class.getResourceAsStream(PATH);
    getting null value in InputStream object 'in'
    I think i am not correctly putting the PATH. Can anybody help me with the Java way of putting the PATH to locate
    resource file at C:/resources/ folder
    Thanks in Advance :)
    You haven't mentioned whether you are using named packages or the default, unnamed one.
    The getClass().getResourceAsStream(propfile) method of java searches all files in the current directory as well as the jar file in which the class file resides.Presumable C:\resources doesn't fit in the first category (it obviously doen't fit in the second).
    In any event, since properties files usually contain the initial configurations for an application, they are essential to the app and should be loaded in the jar, along with the class files, unless there are other compelling reasons.

  • GetResourceAsStream(String name) return null

    Hi!
    jdk1.3
    I want to get InputStream from file. My code is:
    import java.util.*;
    import java.io.*;
    String path = new String("D:" + File.separator
                   + "my_project" + File.separator
                   + "test" + File.separator
                   + "classes" + File.separator + "test.properties");// I set absolute path to file It's necessary for me
    InputStream inputStream = getClass().getResourceAsStream(path);
    Properties prop = new Properties();
    prop.load(inputStream);
    The result is NullPointerException in last row.It's can not find resource. Why?
    Thank you

    Try FileInputStream

  • How to use get getResourceAsStream

    Gday all,
    I gave up trying to comprehend the API doco and tutorials on the How to use get getResourceAsStream. I don't care how the class loader locates resources... I just it to work. Now!
    Here's what works... and what doesn't work...
    package krc.geometry;
    import java.util.Properties;
    import java.io.FileInputStream;
    import java.io.IOException;
    import krc.utilz.io.RuntimeIOException;
    abstract class GeometryProperties {
      private static Properties properties = new Properties();
      static {
        try {
          // properties.load(new FileInputStream("c:/java/home/src/krc/geometry/Geometry.properties")); //WORKS
          // properties.load(new FileInputStream("c:/java/home/classes/krc/geometry/Geometry.properties")); //WORKS
          // properties.load( (new Object()).getClass().getResourceAsStream("krc/geometry/Geometry.properties")); //DOES NOT WORK
          // properties.load( (new Object()).getClass().getResourceAsStream("krc.geometry.Geometry.properties")); //DOES NOT WORK
          // properties.load( (new Object()).getClass().getResourceAsStream("Geometry.properties")); //DOES NOT WORK
          // properties.load( (new Object()).getClass().getResourceAsStream("krc\\geometry\\Geometry.properties")); //DOES NOT WORK
          properties.load( (new Object()).getClass().getResourceAsStream("/krc/geometry/Geometry.properties")); //WORKS
        } catch(IOException e){
          throw new RuntimeIOException("Failed to load GeometryProperties: " + e.getMessage());
      static Properties get() {
        return properties;
      static String getProperty(String key) {
        return properties.getProperty(key);
      public static void main(String... args) {
        System.out.println(GeometryProperties.getProperty("format.double"));
    }I hope someone finds this helpful someday.
    Some related links are:
    http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)
    http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getSystemResourceAsStream(java.lang.String)
    http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getSystemClassLoader()
    http://www.google.com.au/search?hl=en&q=getResourceAsStream+tutorial&meta=&btnG=Google+Search
    http://rachel.sourceforge.net/tutorial.html
    http://forum.java.sun.com/thread.jspa?threadID=5227823&messageID=9928698
    PS: I think the API has ludicrously complicated explanation of something which can be explained succinctly by example... It's a classic case of a "correct" description which only makes sense once you already know how it works. Whomever wrote that one gets 3 out of 10 stars from me... ie No bananas.
    Cheers. Keith.
    Edited by: corlettk on Dec 2, 2007 9:28 AM - typos.

    I've noticed a good google hit rate on this forum, especially on threads with meaningful a subject lines... That's how I found these forums in the first place... I'm hoping that posting solutions and comments here (as well as the occasional question) will make them available to others from google... I doubt that any site I created would earn the same "front page" status as Sun's site.
    Besides, doesn't it still cost money to setup a blog or your own homepage?
    I admit I'm intrigued despite myself... I'm aware that both http://www.joelonsoftware.com/ and http://www.dreamincode.net/ (and problably many others) started as little personal blogs.

  • GetResourceAsStream problem

    I am trying to read text file in a midlet but can not seem to do it. I'm using the wireless tool kit SDK and emulation with Borland JBuilder . I can run the midlet with no problem but can't seem to open the file. Here is a code snippet below. fin is always null, so I suspect that the file is in the wrong location. The directory sturcture is as follows
    -ProjectRoot<dir>
    test.dat<file>
    -src<sub-dir>
    MyMidlet.java<file>
    Can someone tell me where the file should go or what I'm doing wrong in the code? It seems so simple, I know I 'm missing something fundemental here.
    Thanks for your help!
    Cam
    public class MyMidlet extends MIDlet {
    static MyMidlet instance;
    Displayable1 displayable = new Displayable1();
    public MyMidlet() {
    instance = this;
    InputStream fin = this.getClass().getResourceAsStream("test.dat");//tried "/test.dat" as well
    if (fin == null) {
    System.out.println("Fin is Null");
    }else {
    System.out.println("Fin is FOUND");
    try {
    fin.close();
    } catch (IOException ex) {
    ......... other Midlet methods

    With the Wireless Toolkit resources need to be in a "res" subdirectory (at the same level as "src"), or else packaged up into a JAR file.

  • Problem on getResourceAsStream

    i need to acsses pass.dat file from resources folder
    but it dose not working how can i solve this
    try {
             FileInputStream fin=(FileInputStream) getClass().getResourceAsStream("/TestProg/resources/pass.dat");
            ObjectInputStream ois = new ObjectInputStream(fin);
             SecretKey key = (SecretKey) ois.readObject();
             ois.close();
            Encoder encrypter = new Encoder(key);
            encrypter.encrypt(new FileInputStream(filepath),new FileOutputStream(outputFilePath));
            System.out.println("File Encryption Completed !!!");
        } catch (Exception e) {
        }

    Mrkarthick wrote:
    i have Found This Exception
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.io.BufferedInputStream cannot be cast to java.io.FileInputStream
    It would help if you'd provide the whole stack trace, and indicate exactly which line caused the problem, but I assume it's this one:
             FileInputStream fin=(FileInputStream) getClass().getResourceAsStream("/TestProg/resources/pass.dat");You can't just cast any old class to any old other class. You can only cast a reference to a type that the object it points to actually is.
    In any case, you don't need a FileInputStream, since you're not dealing with a file here. Dealing with the file (if the resource even actually is in a file, rather than some other place, like on a web server) is handled for you inside getResourceAsStream.

  • GetResourceAsStream questions

    I'm trying to understand how the file locations work with the getResourceAsStream() method.
    I have properties files for localization. They're kept in the same package (the default package) as my other source code (which is all in a src directory).
    I declare the filenames as such:
    private static String MESSAGESBUNDLE = "/UI_en_US.properties";
    private static String WORDSBUNDLE = "/WORDS_en_US.properties";
    To open the files, I use these 3 lines of code:
    Class clazz = Runtime.getRuntime().getClass();
    in = clazz.getResourceAsStream(_MESSAGES_BUNDLE);
    inW = clazz.getResourceAsStream(_WORDS_BUNDLE);
    Everything works fine until I try to run this application on the web via the MicroEmulator. At that point it can't locate/open the resource files (even though they're bundled into the jar).
    I read in a java forum that the CLASSPATH determines where the jvm looks for the files but I also read the following information (which didn't mention the CLASSPATH--plus I don't have permission to define the value of the CLASSPATH env var running on my ISP anyway).
    In the following quote, the Class definition says that the rules are profile specific: "
    public InputStream getResourceAsStream(String name)
    Finds a resource with a given name. This method returns null if no resource with this name is found. The rules for searching resources associated with a given class are profile specific."
    I looked up this section of the MIDP2.0 spec "Resource names refer to the contents of the MIDlet Suite JAR file. Absolute pathnames, beginning with �/� are
    fully qualified file names within the jar file.
    Relative pathnames, not beginning with �/� are relative to the class upon which getResourceAsStream is
    called...."
    And I experimented with my files a little. I moved the resource files into a package under the /src/ directory and named it 'res'. Thus now I had this directory structure:
    /src/ -- contains all other java classes for my project
    /src/res/ - - contains the resource files such as UI_en_US.properties
    But if I change these lines:
    private static String MESSAGESBUNDLE = "/UI_en_US.properties";
    private static String WORDSBUNDLE = "/WORDS_en_US.properties";
    To refer to the new subdirectory:
    private static String MESSAGESBUNDLE = "/res/UI_en_US.properties";
    private static String WORDSBUNDLE = "/res/WORDS_en_US.properties";
    Then getResourceAsStream() can't locate/open the fies.
    Similarly, if I move the files back to the src directory and make the path relative by removing the leading /:
    private static String MESSAGESBUNDLE = "UI_en_US.properties";
    private static String WORDSBUNDLE = "WORDS_en_US.properties";
    getResourceAsStream() can't locate/open the fies.
    I'd like to understand how the file locating is working--especially so I can run the MicroEmulator on my webpage which will run my J2ME app. on the webpage.
    Any ideas/clarification/etc. would be immensely appreciated!
    jdl

    I must confess I did not read the whole post. But since it is an issue of getResourceAsStream, if you but your properties files into the res directory, then you can access them via getClass().getResourceAsStream("/firstFile.properties") for example.
    I have never used the MicroEmulator (never even heard of it, but this might be my slip), but this should be a general rule. Once you packaged your application into a jar archieve, you should be able to access your properties files like I mentioned without any problems. In the emulator it works, on a real phone it works, so you should be ok.
    When you are usign the method above, the "/" specifies that you are already in the resources folder, so any consecutive folders, like res/localization/english/enFile.properties, can be accessed by using getClass().getResourceAsStream("/localization/english/enFile.properties") Mihai

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

Maybe you are looking for