How to read a text file from a Jar file

Hi
How can I read a text file from a Jar file?
Thanx in advance..

thanx
helloWorld it works.damn, I didn't remove it fast enough. Even if it is urgent, it is best not to mention it, telling people just makes them take longer.

Similar Messages

  • Reading an xml file from a jar file

    Short question:
    Is it possible to read an xml file from a jar file when the dtd is
    placed inside the jar file? I am using jdom (SAXBuilder) and the default
    sax parser which comes with it.
    Long Question:
    I am trying to create an enterprise archive file on Weblogic 6.1. We
    have a framework that is similar to the struts framework which uses it's
    own configuration files
    I could place the dtd files outside the jar ear file and specify the
    absolute path in an environment variable in web.xml which is
    configurable through the admin console.
    But I want to avoid this step and specify a relative path within the jar
    file.
    I have tried to use a class which implements the entityresolver as well
    as try to extend the saxparser and set the entity resolver within this
    class explicitly, but I always seem to sun into problems like:
    The setEntityresolver method does not get called or there is a
    classloader problem. i.e. JDOM complains that it cannot load My custom
    parser which is part of the application
    Vijay

    Please contact the main BEA Support team [email protected]
    They will need to check with product support to determine
    the interoperatablity of Weblogic Server with these other
    products.

  • Executing .jar files from another .jar file.

    How would I run one .jar file from another .jar file. and is there anyway to call specific class arguments? Because I have one .jar file that reads a specified file and returns its contents.
    So how would I execute it and specify its arguments and how would I make it return something to the executing jar file?

    Because I have one .jar file that reads
    a specified file and returns its contents. Presumably you have a class that does that, and you have that class stored in a jar. And you want to know how to... um... do something with that class. I say "um..." because normally you don't execute a class, either, you either call its static methods or you create an instance of the class and call its instance methods.
    If you have been writing a whole lot of little classes each of which just has a static main method, then stop doing that. Write real Java classes instead. The tutorial is here:
    http://java.sun.com/docs/books/tutorial/java/index.html

  • Can't load sql file from inside jar file?

    hi all
    i have a sql file inside my jar file
    and i want to get the path of the sql file to use it in runtime command to restore a sql dump file
    i used the following but it doesn't work:
    the path contains invalid characters such %20% instead of and?
    URL url2=getClass().getResource("backup.sql");
    String str1=url2.toString().substring(10);
    String command="cmd.exe /c  c:\\wamp\\mysql\\bin\\mysql -u root --password=anasa library < "+str1;       
    Runtime.getRuntime().exec(command);is this way is wrong?
    or there's an alternative way?

    How is the system to pull the data out of the jarfile?
    That redirection symbol means to take the information from the file, or here document, or command output that comes after it, but you don't have any of those. It will read that String as if it is a file name, but a file under that name doesn't exist. And, after you've changed it like you have, it doesn't even reference anything inside of a jar file anymore (not that the command could have used that anyway).
    If you insist on doing something like this, then you are going to need to read it with getInputStream and write it out somewhere (probably to a temp file) then use that tempfile and delete it when you're done.

  • How to read the EXIF metadata from a .jpg file

    hi,every one
    Photos which are captured by a digital camera, have some parameters, such as the exposure time,ISO speed rating,camera model,focal length etc.
    How to read this parameters???

    Is it listed in the IIOMetadata?
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.imageio.metadata.*;
    import org.w3c.dom.*;
    public class IIOMetaDataExample {
        public static void main(String[] args) throws IOException {
            URL url = new URL("http://today.java.net/jag/bio/JagHeadshot-small.jpg");
            Iterator readers = ImageIO.getImageReadersBySuffix("jpeg");
            ImageReader reader = (ImageReader) readers.next();
            reader.setInput(ImageIO.createImageInputStream(url.openStream()));
            IIOMetadata metadata = reader.getImageMetadata(0);
            displayMetadata(metadata);
        public static void displayMetadata(IIOMetadata metadata) {
            String[] names = metadata.getMetadataFormatNames();
            for(int i=0; i<names.length; ++i) {
                System.out.println();
                System.out.println("METADATA FOR FORMAT: " + names);
    displayTree(metadata.getAsTree(names[i]), 0);
    public static void displayTree(Node node, int indent) {
    indent(indent);
    String name = node.getNodeName();
    System.out.print("<" + name);
    if (node.hasAttributes()) {
    NamedNodeMap attrs = node.getAttributes();
    for(int i=0, ub=attrs.getLength(); i<ub; ++i) {
    Node attr = attrs.item(i);
    System.out.print(" " + attr.getNodeName() + "=" + attr.getNodeValue());
    if (node.hasChildNodes()) {
    System.out.println(">");
    NodeList children = node.getChildNodes();
    for(int i=0,ub=children.getLength(); i<ub; ++i)
    displayTree(children.item(i), indent+4);
    indent(indent);
    System.out.println("</" + name +">");
    } else
    System.out.println("/>");
    static void indent(int indent) {
    for(int i=0; i<indent; ++i)
    System.out.print(' ');

  • How to read a certificate included in a jar-file???

    Hello,
    I have an application who connects via SSL to a JBoss server. Therefore I need a certificate on the client machine.
    Can I include a selfsigned certificate in the jar file which can be downloaded with webstart???
    If that's possible where can I find the certificate??? For now on my machine I use
    System.setProperty("javax.net.ssl.trustStore","c:/Program Files/.../certificate.truststore");
    I suppose I have to change the path, but I have no idee to where???
    Thanks anyway
    Bart

    Write out the trust store to a file in the temp directory on the client machine when your application starts and instruct the java.net classes to use it by setting the system property just like you described.
    note.. I'm just guessing here
    -Spinoza

  • Include directive to include a JSP file from a JAR file

    I have an Eclipse project in which I have placed a JSP file in the package structure with the rest of my code. This is in fact only a code snippet page, not a full blown JSP file.
    I have a second project that is a Dynamic Web Project in Eclipse that incorporates the first project as a JAR in the /WEB-INF/lib directory.
    In this project I have a JSP file and I want to include the JSP file embedded in that JAR file.
    How do I do that?
    I'm thinking the only real solution is to rewrite the snippet portion as a custom tag.

    The JSP fragment page in question is actually a HTML form page. It is a form to be used specifically by a particular servlet. That is why they are "bundled" together in the same project, in the same package structure.
    I have multiple web applications that I want to include that form/servlet, so it gets added to these projects in the /WEB-INF/lib folder as a JAR library. But I don't want to recreate the form over and over again for each application. It would be nice if I could write a JSP page that wraps the fragment using an include directive to bring that fragment into the new page.
    So to do that with any other fragment I would write:
    <%@ include file="/WEB-INF/jsp/SOME_FORM.jsp" %>
    which works great if my fragment page is in the /WEB-INF/jsp subfolder. But if I want to access the JSP fragment as it is bundled in a JAR file, this:
    <%@ include file="/WEB-INF/lib/FORM.jar/SOME_FORM.jsp" %>
    doesn't work so good. It's just all wrong.
    I was wondering how I could just write one include statement to get what I need. There are work-arounds galore, but I thought if I could get this working it would be the simplest solution overall.

  • Missing class file from tools.jar file!

    I have been playing around with the code:
    import com.sun.tools.javac.v8.JavaCompiler;
    import com.sun.tools.javac.v8.util.Context;
    import com.sun.tools.javac.v8.util.List;
    public class Compiler {
    public static void main(String[] args) {
    JavaCompiler compiler = new JavaCompiler(new Context());
    List list = new List();
    list = list.append("Hello.java");
    try {
    list = compiler.compile(list);
    } catch (Throwable t) {}
    I am running into a problem with the statements:
    import com.sun.tools.javac.v8.util.Context;
    JavaCompiler compiler = new JavaCompiler(new Context());
    The compiler tells me that Context does not exist. I checked the tools.jar file
    and sure enough Context did not exist! Can somebody point me in the right direction as to what I can do to fix this problem!
    Thanks

    Put the jar in your class path.

  • How to read sampled data info from a "*.au"file into an array?

    I need to manipulate the sound file directly using DSP, the first step is to read sampled data from "*.au" file into an array. How can I do that? Thanks a lot!!

    There is a file I/O tutorial in the Java Tutorial (google for Java Tutorial). You can read an .au file as bytes like any binary file.
    Or if you are using the Java Sound API, google for java sound api or java audio tutorial etc etc.

  • Read images from external jar file (Sun's Java L&F Graphics repository)

    Hi!
    I don't know how to read images from an external jar file. Sun has a Java Look and Feel graphics repository that contains a lot of good images that can be used on buttons and so on. This repository is delivered as a jar file, containing only images, and I want to read the image files from that jar file directly without including them inside my application jar file. The application and image jar files will be in the same directory.
    I have absolutely no clue how to solve this. Is it necessary to include the images inside my application jar file or is it possible to have them separate as I want.
    Would really appreciate some help!
    Best regards
    Lars

    Hi,
    There is two ways :
    1) Add your jarfile to the classpath.
    Use the class loader :
    URL url = ClassLoader.getSystemResource("your/package/image.gif");
    Image im = (new ImageIcon(url)).getImage();
    or
    Image im = Toolkit.getDefaultToolkit().getImage(url);2)If you don't want to add the jar to the classpath you can use this (under jdk 1.4):
    import java.util.*;
    import java.util.jar.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class ImageUtilities {
         public static Image getImage(String jarFileName, String fileName) {
              BufferedImage image = null;
              try {
                   JarFile jar = new JarFile(new File(jarFileName), false, JarFile.OPEN_READ);
                   JarEntry entry = jar.getJarEntry(fileName);
                   BufferedInputStream stream = new BufferedInputStream(jar.getInputStream(entry));
                   image = ImageIO.read(stream) ;
              catch (Exception ex) {
                   System.out.println(ex);
              return(image);
    }I hope this helps,
    Denis

  • Urgent help for processing XML stream read from a JAR file

    Hi, everyone,
         Urgently need your help!
         I am reading an XML config file from a jar file. It can print out the result well when I use the following code:
    ===============================================
    InputStream is = getClass().getResourceAsStream("conf/config.xml");
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line;
    while ((line = br.readLine()) != null) {
    System.out.println(line); // It works fine here, which means that the inputstream is correct
    // process the XML stream I read from above
    NodeIterator ni = processXPath("//grid/gridinfo", is);
    Below is the processXPath() function I have written:
    public static NodeIterator processXPath(String xpath, InputStream byteStream) throws Exception {
    // Set up a DOM tree to query.
    InputSource in = new InputSource(byteStream);
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setNamespaceAware(true);
    Document doc = dfactory.newDocumentBuilder().parse(in);
    // Use the simple XPath API to select a nodeIterator.
    System.out.println("Querying DOM using " + xpath);
    NodeIterator ni = XPathAPI.selectNodeIterator(doc, xpath);
    return ni;
    It gives me so much errors:
    org.xml.sax.SAXParseException: The root element is required in a well-formed doc
    ument.
    at org.apache.xerces.framework.XMLParser.reportError(XMLParser.java:1213
    at org.apache.xerces.framework.XMLDocumentScanner.reportFatalXMLError(XM
    LDocumentScanner.java:570)
    at org.apache.xerces.framework.XMLDocumentScanner$XMLDeclDispatcher.endO
    fInput(XMLDocumentScanner.java:790)
    at org.apache.xerces.framework.XMLDocumentScanner.endOfInput(XMLDocument
    Scanner.java:418)
    at org.apache.xerces.validators.common.XMLValidator.sendEndOfInputNotifi
    cations(XMLValidator.java:712)
    at org.apache.xerces.readers.DefaultEntityHandler.changeReaders(DefaultE
    ntityHandler.java:1031)
    at org.apache.xerces.readers.XMLEntityReader.changeReaders(XMLEntityRead
    er.java:168)
    at org.apache.xerces.readers.UTF8Reader.changeReaders(UTF8Reader.java:18
    2)
    at org.apache.xerces.readers.UTF8Reader.lookingAtChar(UTF8Reader.java:19
    7)
    at org.apache.xerces.framework.XMLDocumentScanner$XMLDeclDispatcher.disp
    atch(XMLDocumentScanner.java:686)
    at org.apache.xerces.framework.XMLDocumentScanner.parseSome(XMLDocumentS
    canner.java:381)
    at org.apache.xerces.framework.XMLParser.parse(XMLParser.java:1098)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.
    java:195)
    at processXPath(Unknown Source)
    Thank you very much!
    Sincerely Yours
    David

    org.xml.sax.SAXParseException: The root element is required in a well-formed document.This often means that the parser can't find the document. You think it should be able to find the document because your test code could. However if your test code was not in the same package as your real (failing) code, your test is no good because getResourceAsStream("conf/config.xml") is looking for that file name relative to the package of the class that contains that line of code.
    If your test code wasn't in any package, put a slash before the filename and see if that works.

  • How to read, write file inside the JAR file?

    Hi all,
    I want to read the file inside the jar file, use following method:
    File file = new File("filename");
    It works if not in JAR file, but it doesn't work if it's in a JAR file.
    I found someone had the same problem, but no reply.
    http://forum.java.sun.com/thread.jsp?forum=22&thread=180618
    Can you help me ? I have tried this for all night !
    Thanks in advance
    Leo

    If you want to read a file from the JAR file that the
    application is packaged in (rather than a separate
    external JAR file) you do it like this ...
    InputStream is =
    ClassLoader.getSystemResourceAsStream("filename");Better to use
    this.getClass().getClassLoader().getResourceAsStream();
    From a class near to where the data is. This deals with multiple classloaders properly.

  • Running scripts, bat files, etc from a jar file

    Hello,
    Does anyone know of a way, or even if it is possible to run a script or batch file from a jar file?
    For instance, lets say I have a batch file that I can run from the command prompt by typing :
    myBatchFile.bat
    and now I write a very simple java app that will do the same:
    public class Test {
    public static void main(String[] args) {
    try {
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec(�myBatchFile.bat�);
    } catch (Exception e) {
    e.getMessage();
    The above app will work as long as the batch file is in the current directory, but how or can I make it work if I stick the batch file in a jar file along with the app?
    I tried using the manifest file with no luck.
    I tried creating a URI to the jar file, wrapping it in a File and then passing that File to the exec method also with no luck.
    I searched all the forums on Sun but came up with nothing.
    I performed a google search also with no luck.
    Does anyone have the answer to this? Even if I can get a definitive �No it can�t be done� answer. Although I would think that it should be able to be done.
    Thanks

    Hi,
    you cannot execute anything being inside a jar-file. The OS doesn't know anythig about jar-files and cannot look inside one to find the program/script/batch you want to execute.
    You could do a workaround by extracting the file from the jar-file before calling exec(). But normally OS dependent files should not be inside a jar-file and remain in a own directiory.
    Andre

  • Updating a properies file in a .jar file

    Hi
    I have an application that reads a properties file from a .jar file using the getSystemResourceAsStream method on the ClassLoader class. What I would like to be able to do is to change values in this properties file when the application exits so the next time into the application the last used values for certain text boxes are remembered from last time. Can anyone suggest a way to achieve this. I can write the properties file out using the FileWriter class and this works but I read it is not a good idea to use these classes for this purpose.
    Thanks in advance

    Those .properties files can perfectly be writting using a FileOutputStream
    (not a Writer). Updating a .properties file in a .jar file isn't possible
    without rewriting the entire .jar file.
    Your scenario should work fine: if the .properties file doesn't exist, get
    a "prototype" from the .jar file and store it as an independent file. Update
    this file using a FileOutputStream ad lib.
    kind regards,
    Jos
    ps. if you don't like this scenario, you could have a look at the Preferences class.

  • How to read a text file from other machine???

    I have a text file located in local machine. I use th e code below to retrieve data from that particular text file.
    String realPath     = (String)getServletContext().getRealPath("");
    BufferedReader holsFile = new BufferedReader(new FileReader(realPath + "/webpages/holidays.txt"));My question is , how could I retrieve the records from the tsxt file if the file is located in another machine or webserver?
    Thanks for advanced.

    It's ok to be new.
    The answer is yes. (But I'll let you look in the javadoc to see which package it's in).
    Also it may be worth understanding that there is no such thing as a "function" in java, operations are termed "methods". To go further, you should realise that URL is a class not a "function" or method. The parentheses mean you're calling the constructor.
    HTH
    /k1

Maybe you are looking for