Class.getResource(String)....how to use it?

I know i nedd to use this to access some wav files in a jar, but i can't figure out how. Could some kind person give me a demo.
my wav file is called "boring.wav" it's in the same directory as the class file. How do implement the code to access this file from the jar archive?
thanx
Peter

Use
ClassLoader classLoader =
ClassLoader.getSystemClassLoader();
URL propsURL = classLoader.getResource(fileName);
inStream = propsURL.openStream();
Then read the contents from the stream
ClassLoader looks for resources in the classpathLooks good. I just wanted to make a quick note. The System Class Loader is the bootstrap classloader that loads up the class containing main. Some deployment systems (Java Web Start) imediately start up thier own class loader to do the rest of the work. So the system class loader becomes useless. In these cases you would use this.getClass().getClassLoader() instead. It's a small point, but Jars were asked about. ;)

Similar Messages

  • Sharepoint 2013 :Content Search Web part Property Filter By Query String - How to use ?

    Hi,
    I would like to filter data that is displayed in content search web part  by using  URL.
    I tried to use Value of a parameter from a URL - Query String.Parameter1
    But have no idea how to use it.
    Can someone help me pleas ?

    duplicate thread
    http://social.msdn.microsoft.com/Forums/en-US/f9fef155-1aa3-43b5-b285-5eae5d036b8d/content-search-webpart-property-filter-by-query-string-how-to-use-?forum=sharepointgeneral
    My Blog- http://www.sharepoint-journey.com|
    If a post answers your question, please click Mark As Answer on that post and Vote as Helpful

  • Content Search Webpart Property Filter By Query String - How to use ?

    Hi,
    I would like to filter data that is displayed in content search web part  by using  URL.
    I tried to use Value of a parameter from a URL - Query String.Parameter1
    But have no idea how to use it.
    Can someone help me pleas ?

    Hi,
    I am looking for solution to filter data on content search web part ( SP 2013)  by using  URL.
    For example:
    My URL is: http://SiteCollName/Sitename/Pages/PageName.aspx?MyParameter1=XXXX
    Result : Display results that field "My field" contains XXXX.
    nikita

  • Do you have classes to learn how to use I pad

    Do you have classes in Reno nv to use the I pad

    You are not talking to Apple here - just other users who are here to help each other sort through problems with the iPad. All Apple Stores have Genius Bars where you can book an appointment with an Apple Genius if you want one on one instruction with the iPad.
    Apple Retail Store - Summit Sierra
    There are many tutorials that you can watch online starting with Apple's iPad guided tours.
    Apple-iPad 2-Guided Tours
    You can Google for even more tutorials or just click on this.
    This is what Google came up with when I entered iPad online tutorials in the search field

  • Class extends JComponent how to use custom methods?

    I have a class Block which extends JPanel
    code is hereprivate class Block extends JLabel{
              boolean top;
              Block(int a,Color c){
                   setSize(40 + a*10,20);
                   setBorder(BorderFactory.createMatteBorder(40+a*10,0,0,0,c));
              void setTop(boolean b){
                   this.top = b;
              boolean getTop(){
                   return top;
         }I need to use getTop() method of certain block in class implementing MouseMotionListener
    I used getComponent() method like this
    e.getComponent().getTop()but it didn't work and gave
    HanoiTowers.java:59: cannot find symbol
    symbol : method getTop()
    location: class java.awt.Component
    if(e.getComponent().getTop()){}
    error
    Is there some other way to do this?

    Antti_ wrote:
    I have a class Block which extends JPanelahem, I believe that it extends JLabel.
    Is there some other way to do this?You could cast I suppose:
              Component c = e.getComponent();
              if (c instanceof Block)
                System.out.println(((Block)c).getTop());
              }

  • How to use string class?

    Hi, experts:
    Have you run HelloStrings sample in "Thinking in C++" book? The source code is following. But when I compile, it throws error:"string in not defined". How to write correct makefile? Thanks! /Denise
    //: C02:HelloStrings.cpp
    // The basics of the Standard C++ string class
    #include <string>
    #include <iostream>
    using namespace std;
    int main() {
    string s1, s2; // Empty strings
    string s3 = "Hello, World."; // Initialized
    string s4("I am"); // Also initialized
    s2 = "Today"; // Assigning to a string
    s1 = s3 + " " + s4; // Combining strings
    s1 += " 8 "; // Appending to a string
    cout << s1 + s2 + "!" << endl;
    } ///:~

    The most likely cause is that the "using namespace std;" line is missing from the file you are compiling, or commented out.
    Using C++ 5.6 and the exact file I listed earlier, I get this result:
    % CC -V hello.cc
    CC: Sun C++ 5.6 2004/06/02
    /set/mercury/dist/fcs.2/sparc-S2/opt/SUNWspro/prod/bin/c++filt: Sun C++ 5.6 2004/06/02
    ccfe: Sun C++ 5.6 2004/06/02
    ld: Software Generation Utilities - Solaris Link Editors: 5.9-1.377
    Copy/paste the hello.cc file I listed above and try compiling it.
    If you still get errors, your compiler was not installed correctly, or the installation has become corrupted.
    If you want to poke around a bit more before re-installing, try this:
    CC -H -c HelloStrings.cc |& grep string
    The -H option lists all the header files that were read. You should see this, assuming your compiler is installed in /opt:
    /opt/SUNWspro/prod/include/CC/Cstd/./string <------- string header
         /opt/SUNWspro/prod/include/CC/std/string.h
              /usr/include/string.h
                   /usr/include/iso/string_iso.h
         /opt/SUNWspro/prod/include/CC/Cstd/rw/string_ref
    If in particular you do not see /opt/SUNWspro/prod/include/CC/Cstd/./string, or if the "string" header marked above comes from some other location, something is definitely wrong with the compiler installation.
    If you see the correct string header, run "wc" on that header. You should see this:
    1858 6099 68105 string
    If not, the string header is corrupted.
    To re-install, refer to the Installation Guide that comes with Sun Studio 9. Follow the instructions for uninstalling Sun Studio 9. Then run the product installer, paying close attention to any warnings or error messages. I strongly recommend using the product installer, and not trying to install the product yourself directly from the packages.

  • How to use class.getResource() to create an ImageIcon

    Hi,
    I am well acquainted with creating and using ImageIcon icons using the ImageIcon constructor
    and putting the image file in a folder called Images which is at the same level as the
    bin and src folders.
    I discovered a demo program, LayeredPaneDemo, that uses class.getResource() to create
    an icon and found that in my eclipse version, the icon's image file was not found when
    I used the original getResource() call but the icon was created when I used the ImageIcon
    constructor.
    I posted on JavaRanch and eventually realized that the image file needed to be with the
    .class files, so I moved the Images folder under bin and getResource() works fine and I'm
    happy.
    However, I have three questions for you.
    One poster on JavaRanch told me that it's better to use getResource() rather than the
    ImageIcon constructor for distributing an app (I'm not distributing anything but want
    to do it all correctly).
    Do you agree with that or can I safe keep using the ImageIcon constructor?
    Another poster told me he doesn't think it's safe to leave the image file in bin because
    it might be lost during the build in eclipse and that there is a way to have eclipse copy
    the files to bin during the build which should mean that I can leave the images folder at
    the level of bin and src.
    Do you agree with that?
    If yes, how do I get eclipse to copy the file during the build?
    P.S.
    Before I posted on JavaRanch, I put the Images folder at every level of the project's
    directory as shown in eclipse (which is why I missed the bin folder until JavaRanch
    whacked me upside the head) and getResource() still didn't work.

    The contents of the Java Source folder are compiled if they're source files, copied otherwise (assuming no filter's been put in place to prevent copying), so your images belong under a source folder.

  • How to use replace(CharacterSequence, CharacterSequence) in String class

    Need simple java program using the following
    how to use replace(CharacterSequence, CharacterSequence) in String class
    Kindly help

    From http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#replace(java.lang.CharSequence,%20java.lang.CharSequence)
    replace
    public String replace(CharSequence target,
    CharSequence replacement)Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
    Parameters:
    target - The sequence of char values to be replaced
    replacement - The replacement sequence of char values
    Returns:
    The resulting string
    Throws:
    NullPointerException - if target or replacement is null.
    Since:
    1.5

  • How to use the different class for each screen as well as function.

    Hi Experts,
    How to use the different class for each screen as well as function.
    With BestRegards,
    M.Thippa Reddy.

    Hi ThippaReddy,
    see this sample code
    Public Class ClsMenInBlack
    #Region "Declarations"
        'Class objects
        'UI and Di objects
        Dim objForm As SAPbouiCOM.Form
        'Variables
        Dim strQuery As String
    #End Region
    #Region "Methods"
        Private Function GeRate() As Double
                Return Double
        End Function
    #End Region
    Public Sub SBO_Appln_MenuEvent(ByRef pVal As SAPbouiCOM.MenuEvent, ByRef BubbleEvent As Boolean)
            If pVal.BeforeAction = True Then
                If pVal.MenuUID = "ENV_Menu_MIB" Then
                End If
            Else ' Before Action False
                End If
        End Sub
    #End Region
    End Class
    End Class
    Rgds
    Micheal
    Vasu Anna Regional Feeling a???? Just Kidding
    Edited by: micheal willis on Jul 27, 2009 5:49 PM
    Edited by: micheal willis on Jul 27, 2009 5:50 PM

  • How to use application class reference in the controller methods of BSP

    Hi,
    I have created a bsp application and also created an application class and assigned it to the application class. In the application class, I have created attribute TEXT type string(public and instance parameter).
    In the controller let's say main.do, I am trying to give a value to to the text by adding the following code.
    application->text = 'test'.
    I am getting syntax error saying field 'text' is unknown. It is not contained in one of the specified tables nor defined by DATA statement. 
    Please can someone let me know how to use the application class in the coding with an example. I couldn't find how exactly this has to be reference. Please help.
    Best regards
    Siva

    Hi,
    if you are having main controller and sub-controller then you may need to use below coding to use application class reference.
    *Data declaration
      DATA:  obj_cntrl        TYPE REF TO cl_bsp_controller2,
             obj_sub_cntrl   TYPE REF TO z_cl_sub_cntl,
             application TYPE REF TO z_cl_application.
    *Get the controller
      CALL METHOD obj_main_cntrl->get_controller   "obj_main_cntrl is the object of main controller
        EXPORTING
          controller_id       = 'SUB'   "Controller ID
        RECEIVING
          controller_instance = obj_cntrl  .
      obj_sub_cntrl ?= obj_cntrl  .
      application ?= obj_sub_cntrl ->application.
    or simply use below code in your controller method.
      application ?= me->application.
    Thnaks,
    Chandra

  • Class.forName, how to use it in the case?

    we have a java application:
    c:\app\TestForName.class
    inside the app, there is a call:
    Class.forName("ClassLib");
    ClassLib.class is a simplest class for testing with no package.
    ClassLib.class can be in any directory except the app's directory
    c:\app
    because ClassLib.class stands for our library class for multiple projects and multiple uses, it is not allowed to be in a special app directory.
    and, ClassLoader and URLClassLoder are not suitable in our case.
    i tried following 3 ideas, none of them is OK, please help.
    1. put ClassLib.class in directory
    c:\lib\
    (that is c:\lib\ClassLib.class)
    call application with command -cp
    java -cp c:\lib;....; TestForName
    (method Class.forName("ClassLib") call is inside TestForName.class)
    2. put ClassLib.class in
    c:\jdk\bin\
    (VM says it is one of "java.library.path")
    java -cp ....; TestForName
    3. put ClassLib.class in
    c:\jdk\JAR\classes\
    (VM says if is one of "sun.boot.class.path")
    java -cp ....; TestForName
    i really wondering how to make Class.forName() call successfuf inside application TestForName.class
    1. which directory is right place for ClassLib.class
    2. how to change command line or java code inside TestForName.class
    thx for any help.

    Why don't u use a class loader. Try this code
    // loader class
    public class Loader  extends ClassLoader {
        String path;
        public Loader(String path) {
              this.path = path;
        public Class findClass(String name) {
            byte[] b = loadClassData(path+name+".class");
            return defineClass(name, b, 0, b.length);
        private byte[] loadClassData(String name) {
            File file = new File(name);
            byte[] data = null;
            try {
                InputStream in = new FileInputStream(file);
                data = new byte[ (int) file.length()];
                for (int i = 0; i < data.length; i++) {
                    data[i] = (byte) in.read();
            catch (IOException ex) {
            file = null;
            return data;
    // in your caller class use
       Loader loader = new Loader(libPath); // lib path may be taken from a command line arg
       Object main = loader.loadClass("ClassLib", true).newInstance();I think this is what u r looking for
    Uditha Nagahawatta

  • How to use an instance instead of the class itself

    I am building a program but have a problem.
    My program uses a controller class which instantiates a World-class. In the world class has a Vector I make a Vector in which I place all the elements in the world. (I also made an Element class from which all the objects that I put into this Vector extend.)
    Everything except for some methods in the controller class are declared public. I might need to use static, but I do not know how.
    // CONSTRUCTOR CONTROLLER CLASS
    world = new World ();  // instantiate one and only one world
    world.newElement (new Beamer ("beamer", 20. , 20.));  // use a selfwritten method to add a "Star Trek"-like
                              // beamer to the world. I give it a name and position.
    world.newElement (new Avatar ("avt", "beamer"));  // add an avatar which is "beamed up". so what I do is that I use the beamer for the beginposition of the avatar. However, and this is my problem, in the constructor of Avatar (see below) i need the beamer in world, but my compiler cant find world. I probably need to import my World or controller class, but even then: I do not understand how to use an instance (world is an instance. I cant use the World-class as the class does not contain the beamer element)
    public class Avatar extends Element {
         public Avatar (String n, String beamer){
              name = n;
              posx = world.named("beamer").getPosx; // the selfwritten method named finds the
                // element in the Vector that goes with the name. Any ideas to make this code better are welcome too.
              posy = world.named("beamer").getPosy;
    } Any ideas on how to solve this (common) problem in good coding are most welcome.

    I think you are best off if you use static methods and static fields only in your World class. That way you don't have to instantiate it and everyone has access to its methods. This would be then completely analogous to how you access methods and fields of the well-known class System (e.g. when you use System.out.println). This also has the advantage that you are guaranteed to have only one copy of the World.
    Here is an example of how your World class, Avatar class and main code would look like.
    Main code: (note the use of capital W in the name World, referring to class rather than instance).
    // no need to instantiate World, as we call its static methods only
    World.newElement (new Beamer ("beamer", 20. , 20.));
    World.newElement (new Avatar ("avt", "beamer"));  // add an avatar which is "beamed up". World class: (note the static keyword in front of the vector and the methods)
    public class World {
      private static Vector v;       // static field, only one copy of it ever exists
      public static void newElement(Element e)   // static method, can call without instantiating world
         v.addElement(e);
      public static Element named(String n)  // use to look up elements
         ... some code which goes through v and finds element named "n" ...
         ... return reference to that element ...
    }and finally the Avatar: (again note the use of reference to World as a class rather than instance)
    public class Avatar extends Element {
         public Avatar (String n, String beamer){
              name = n;
              posx = World.named("beamer").getPosx;
              posy = World.named("beamer").getPosy;
    } The above example is how I would implement it when you don't actually need instances of the World class.

  • How to use URL class instead of Socket

    Hi all. I am developing a small inventory control system for a warehouse.
    I am suing a Java desktop application that connects to a servlet via Internet.
    I have been searching the net how to use JSSE for my application since i am new to secure sockets and JSSE.
    Since I havent implemented security In my current system yet, i am using URLConnection conn = url.openConnection(); to connect to a servlet.
    However, in a good tutorial that I found about JSSE, sockets are used directly for connection, insted of URLCOnnection. They use the code like this: SSLSocketFactory sf = sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket)sf.createSocket( host, port ); Since, using sockets is overly complex for me, I want to make use of the URLConnection class instead to keep it simple.
    Could anyone please tell me how to make use of the URLConnection class to establish secure http connection.
    by the way, the tutorial is here:
    http://www.panix.com/~mito/articles/articles/jsse/j-jsse-ltr.pdf
    thanks.

    Here you go. The following code snippet allows you post data to http URL. If you have to do the same to https URL , please let me know.
    OutputStream writeOut = null;
    HttpURLConnection appConnection = null;
    URL appUrlOpen = null;
    //data to be posted.
    String data = "This is the test message to post";
    byte[] bytesData = this.data.getBytes();
    appUrlOpen = new URL(""Your Servlet URL");
    appConnection = (HttpURLConnection) appUrlOpen.openConnection();
    appConnection.setDoOutput(true);
    appConnection.setDoInput(true);
    appConnection.setUseCaches(false);
    appConnection.setInstanceFollowRedirects(false);
    appConnection.setRequestMethod("post");
    appConnection.setRequestProperty("Content-Type","application/text");
    appConnection.setRequestProperty("Content-length", String.valueOf(bytesData.length));
    writeOut=appConnection.getOutputStream();
    writeOut.write(bytesData);
    writeOut.flush();
    writeOut.close();
    String inputLine;
    StringBuffer sb = new StringBuffer();
    reader = new BufferedReader(new InputStreamReader(appConnection.getInputStream()));
    char chars[] = new char[1024];
    int len = 0;
    //Write chunks of characters to the StringBuffer
    while ((len = reader.read(chars, 0, chars.length)) >= 0)
    sb.append(chars, 0, len);
    System.out.println("Response " + sb.toString());
    reader.close();
    sb=null;
    chars = null;
    responseBytes = null;
    ******************************************************************************************

  • How to use java class in pl/sql

    Hai Guys,
    here is my java class:
    import java.io.*;
    public class ListFiles
    public static void main (String[] args)
    File file=new File("C:\\");
    File[] files=file.listFiles();
    for(int fileInList=0; fileInList<files.length; fileInList++ )
         System.out.println(files[fileInList].toString() );
    i want to use this class in pl/sql, i am new about this topic my concern are following
    how to load java class
    how to use in pl/sql
    Guys i'll be great-full to you if you could help me out or share link or document .

    First Read https://forums.oracle.com/forums/ann.jspa?annID=432
    Check this link...
    1. http://www.devshed.com/c/a/Oracle/Extending-PLSQL-with-Java-Libraries-concluded/
    2. calling java from pl/sql in oracle 10g?its very urgent.
    3. http://qamarsyed.blogspot.com/2010/07/calling-java-from-plsql-inside-oracle.html
    4. http://home.c2i.net/toreingolf/oracle/java_and_plsql.htm
    Hope this helps...
    If someone response is helpful or correct, please mark it accordingly.

  • How to print a string with out using main method??

    how to print a string with out using main method??
    if we can tell me with example?
    thanks in adavance
    raja

    Hi,
    actually there's none. The UITableView class needs to "know" the tableView's height so either it can calc <number of rows> times <row height> or it has to sum the height of each single row.
    If the row which needs to be of different size always is the first or the last row you can user a tableHeader or tableFoot view.
    Regards
    Dirk

Maybe you are looking for

  • [SOLVED] GNOME Shell 3.4 : Volume Control Missing

    Hi all, I have an Acer netbook with Arch Linux i686. I installed GNOME-Shell 3.4, but there is no volume control applet. When playing music, i can't control the volume. Can you help me? (Sorry for my bad English) Last edited by masnormen (2012-06-05

  • Headins are not displaying in Quality Server

    Hi Friends, 1. iam develpoed one report it is displaying output in 210 sever when i moved it to quality sever, it is not displaying output headings like sales order, customer,approved..., it displaying remaining data except headings....why it happens

  • MAIL RECEIPT in Mail Package

    Hi, Iam using Mail package to send the mail .There is a structure MAILRECEIPT in mail package.How to get the response in the mail structure. Do we need to do some settings in Receiver mail adapter to obtain the Receipt ? Please help . Thanks and Rega

  • Trailing space issue in Unix File

    Hi All, I am facing an issue with the trailing space in Unix file content. When the file is being created in Unix server the trailing space is getting trimmed automatically. As per the requirement,this space should be retained in the Unix file as it

  • Oracle Pipes- 10g RAC?

    Oracle Pipes is not working on 10g RAC?