Accesing a file in the Jar archive

Hello, I am new to Java and I have a problem with my program.
I am writing an application that among other things can read text files.
Every thing works fine as long as run the .class
If I pack the application into a .jar executable (with the text files inside)
I can not reach the files any more.
Probably I am doing something wrong during the packing...
//this is the constructor
public Antenna(File fos){
     try{
     FileReader oos = new FileReader(fos);
     BufferedReader filebuf = new BufferedReader(oos);
                     //I do something with the file
           oos.close();
            } catch (IOException e) {
                                          JOptionPane.showMessageDialog(this,
          "File: " + fos + " NOT FOUND", "Warning",               JOptionPane.ERROR_MESSAGE); }
//I use something like this to initialize my class
Ant1 = new Antenna(new File("Curzola.ant"));When I run my application like .jar (that contains the "Curzola.ant") I get the error unless the file Curzola.ant is external to the jar file in the same directory as the -jar file.
Does someone know what I am getting wrong?
I think it should be easy!!
Thanks
carlo

If you want to read a text file line-by-line, BufferedReader is a good choice.
If you have a InputStream, you can use classes from java.io to convert an
input stream into a BufferedReader:
InputStream -> InputStreamReader -> BufferedReader
For example:
void f(InputStream in) throws IOException {
    Reader r = new InputStreamReader(in, "ISO-8859-1");
    BufferedReader br = new BufferedReader(r);
    //use br
}Some coders would use a different InputStreamReader constructor:
Reader r = new InputStreamReader(in);But that uses the platform's default charset encoding, and since we are
talking about a file in your jar, you shouldn't assume it's being decoded
on the same platform it was encoded.
Your original code, by the way, used FileReader, which is just a convenience
subclass of InputStreamReader, and your code:
FileReader r = new FileReader(file);was just shorthand for
InputStream is = new FileInputStream(file);
Reader r = new InputStreamReader(is);Finally, what objects should your constructor accept? One approach
is to be super flexible and accept many types:
public class Example {
    public Example(URL url) throws IOException {
        this(url.openStream());
    public Example(File file) throws IOException {
       this(new FileInputStream(file));
    public Example(InputStream in) throws IOException {
        this(new InputStreamReader(in, "ISO-8859-1"));
    public Example(Reader r) throws IOException {
        BufferedReader br = new BufferedReader(r);
        //use br
}The other extreme is to accept one basic type. In your case, since you want to read text, is to accept a Reader:
public class Example {
    public Example(Reader r) throws IOException {
        BufferedReader br = new BufferedReader(r);
        //use br
}...and have the calling code do the work of constructing an appropriate reader.

Similar Messages

  • Not able to view the uploaded PAR file in the portal archive selection.

    Dear All,
    I have modified com.sap.portal.runtime.logon.par and have renamed it to some other name.
    Now I have uploaded the par file.
    The problem is that when choose new from PAR option (to create iview from a par file),I am not able to see the par file in the Portal Archive selection.
    I also want to know that if I am able to call the par file in the iview, can I use this iview to have a portal login.
    Our requirement is that we want to give login page for the portal in the portal home page.The portal home page will be for the anonymous users.
    Kindly try to guide me

    Hi Nitin,
    Check ur Portalapp.xml file. If u have the following code in that just <b>remove</b> them
    <property name="com.sap.portal.pcm.Category" value="platform">
    <property name="inheritance" value="final"/>
    Deploy it again.now u can see that par in ur portal.Refer this thread also
    PAR File not seen
    Regards,
    Tamil K

  • Java Files inside the jar file cannot be read or accessed through Eclpse

    The Java File inside the jar file of the eclipse cannot be accessed through the Eclipse . It shows error for the modules in the jar file .
    But when compiled with adding the jar files to the class path the compilation is successful .
    How can i browse through the files in the jar like going into the function definition .
    TIA ,
    Imran

    Open MPlayer OSX and show the playlist (command-shift-p) then drag the file into the playlist. Click the file in the playlist and click the "i"nfo button. What does it list for file, video and audio format?
    Not all of the codecs used in avi and wmv files are available for OS X so I'm guessing your file happens to be using one that isn't...

  • How to read some files inside the jar

    Hi,
    I have an applet that runs with JWS. The user can input some information and then I need to show this information in a web page. As the application can be run offline, I cannnot use JSP�s to generate the web page. The information is saved in a xml file, so I use a xsl parser to generate the html code. The problem is that I have to include some javascript files (.js). I put these files inside the jar, but, how can I read these files, or how can I reference these files from inside the html page ?
    Thanks !

    You can use getClass().getResource(classpath)
    to get a stream version of the data from your
    jar file. If you need to put it in a file, you
    can write that stream to a file in a temp directory.
    classpath is the classpath of your js file

  • How to read files outside the jar ?

    Hi all,
    One of my classes inside jar needs to read XML file that resides in the same location where the jar sits. I use MyClass.getClass().getResource("MyXMLFile.xml") but it keeps returning null.
    If I place the XML file inside the JAR, I can find it using above methods, but since I want the user to easily edit the XML file without opening the jar file and detach the XML file, I choose not to include the XML file inside the jar.
    Any help would be greatly appreciated.
    Setya

    Thanks for the dukes.
    My JDBC post on this forum discusses the issues of
    using Class-Path in your jar file. It works, but it
    may vary from system to system.
    Thanks also from my side: I have read recently your discussion about reading files in the jar's directory, since I had the same problem. So I was really glad to see your solution. However, I had one more problem, namely that I'm running my application sometimes from the jar, sometimes from the classes directly (debugging). In order to have always the correct path (although a different one) I have added some more lines to deal with that case. I hope that will be useful for you as well!
    Dieter Profos
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.net.URL;
    * @author pkwooster
    * @author Dieter Profos
    * @version 1.01 04/03/26
    public class ReadOutside extends Frame {
    private TextArea textArea;
    public static void main(String[] args) {
    // Create application frame.
    ReadOutside tc = new ReadOutside();
    tc.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    System.exit(0);
    // Show frame
    tc.setSize(600,250);
    tc.setVisible(true);
    public ReadOutside() {
    textArea = new TextArea(20,80);
    add(textArea);
    readOutside(this);
    public void readOutside(Object o) {
    System.out.println(getCodeBasePath(o));
    /** Gets the absolute path of the directory where the JAR or CLASS file is
    * located. If the application is run from a jar file, the directory of the
    * jar file is returned; if it is run from a class file, the method will
    * return the directory path of the class file.
    * @param o The main class of the application.
    * @return The absolute directory path, or null if neither the class nor a
    * jar file could be found.
    public String getCodeBasePath(Object o) {
    Class c = o.getClass();
    URL url;
    // get the class name
    String className = c.getName();
    textArea.append("class name = " + className + "\n");
    // replace package periods by file separators
    className = className.replace('.','/');
    ClassLoader cl = c.getClassLoader();
    if (cl == null)
    cl = ClassLoader.getSystemClassLoader();
    url = cl.getResource(className + ".class");
    String xPath = url.toExternalForm();
    textArea.append("url = " + url + "\n");
    textArea.append("extPath = " + xPath + "\n");
    // make sure that the path starts with jar:file:
    if (xPath.startsWith("jar:file:")) {
    // remove jar:file: + the subsequent file separator
    xPath = xPath.substring("jar:file:".length()+1);
    int n = xPath.indexOf("!");
    if (n < 0)
    n = xPath.length();
    String jarPath = xPath.substring(0, n);
    textArea.append("jar file path = " + jarPath + "\n");
    n = jarPath.lastIndexOf("/");
    String jarDir = jarPath.substring(0, n+1);
    textArea.append("jar dir = " + jarDir + "\n");
    return jarDir;
    else { // if program is run from its class file (development phase!)
    if (xPath.startsWith("file:")) {
    // remove file: + the subsequent file separator
    xPath = xPath.substring("file:".length()+1);
    textArea.append("class file path = " + xPath + "\n");
    int n = xPath.lastIndexOf("/");
    String classDir = xPath.substring(0, n+1);
    textArea.append("class dir = " + classDir + "\n");
    return classDir;
    return null;

  • How to read a file inside the JAR file

    Hi All,
    I want to save some preferences in a file called "preferences". I kept the preferences file under my java package.
    If i am running the code inside the NetBeans 6.9 IDE it's working file. But once i have created a JAR and try to run the application, it couldn't find the path.
    Please help me that how to resolve this issue. I don't want to save this preferences file outside of my JAR (i.e) within my java package.
    Here is the code,
    package mypackage;
    import java.io.BufferedReader;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    public class ReadFile
        private void writeFile()
            try
                OutputStream out = new FileOutputStream(getClass().getClassLoader().getResource("mypackage/preferences").getPath().replace("%20", " "));
                PrintWriter writer = new PrintWriter(out);
                writer.println("Hello Java!");
                writer.close();
                out.close();
            catch (Exception ex)
                System.out.println(ex.getMessage());
        private void readFile()
            try
                FileInputStream fi = new FileInputStream(getClass().getClassLoader().getResource("mypackage/preferences").getPath().replace("%20", " "));
                BufferedReader br = new BufferedReader(new InputStreamReader(fi));
                System.out.println(br.readLine().trim());
                br.close();
                fi.close();
            catch (Exception ex)
                System.out.println(ex.getMessage());
        public static void main(String[] args)
            ReadFile read = new ReadFile();
            read.writeFile();
            read.readFile();
    }If i run the JAR, i get the following error message,
    {color:#ff0000}*file:\my jar path\jarname.jar!\mypackage\preferences (The filename, directoryname, or volume label syntax is incorrect)*{color}

    Thanks sabre150,
    sabre150 wrote:
    You cannot update a running jar file. I am sorry. I didn't know about it. Thanks to point out.
    There are two ways I approach this depending on my exact requirements -
    1) use the java.util.prefs.Preferences APII will try this one
    >
    2) if not already present I copy the preferences file from the jar to a known place. I use a directory in the user's home directory and normally make the directory name the program with a '.' prefix.
    One cannot access files in a jar file using the File API. One needs to use the getResource() or getResourceAsStream() methods on Class or ClassLoader.

  • 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.

  • Updating an XML file inside the Jar executable

    Hello all!
    I would like to ask how can i update an XML file that is packaged inside my jar file?
    For intstance:
    I have a Java Application in NetBeans
    Inside a package i have constructed a custom .xml file.
    I can read from this file using
    .....getClass().getResourceAsStream("/.../file.xml")and after that using XPath for querying and works fine.
    I want to update an entry in my xml file so the jar contains now the newly updated file.
    Thanks everyone who spends his time to read this. Hope someone can help me.

    Even if it were possible, it would be a bad idea. A jar file is something you deploy. It can be really hard to manage ongoing maintenance if the thing you deploy changes after you've deployed it.
    Just create a file, in an appropriate place given the user's OS, to hold data that changes after the jar has been deployed. Your application will still be in a single jar; it's just that the application will happen to create additional content outside the jar.

  • Reading a file in the JAR

    i have a jar with class files and xml files in it. my application uses this jar and a particular class has a link to the xml. but while compiling, it shows path not found. the application couldnt read the xml file in the jar. how to set the path or read the xml file
    XML file in JAR:
    SQLMaps/admin/sample.xml [folder structure inside the jar file]
    my application has a path like SQLMaps/admin/sample.xml
    but how do we point to the xml file in the jar
    Regards
    Pradheep

    thanks anyway
    but i need the application to read the xml file in the jar file
    to be more clear.
    the jar file has xml in a specified folder.

  • How to modify the Manifest file in the JAR file

    Hi guys,
    i am having a JAR which contains one Manifest file and 10 class files.
    actually i want to do some changes on the manifest file, but by using the ,
    " jar -cmf new_manifest_file jar_fileName all_class_files " option i am able to modify the manifest file by repacking the .class also.
    i want to modify the manifest file without disturbing the existing class files in the JAR file.
    Thanx in advance.............! ! ! !
    bye,
    subbu

    yeah, that is correct.
    my doubt is,
    Is it possible to modify the Manifest file which is inside the jar file, by without disturbing the Class files.
    --Subbu                                                                                                                                                                                                                                                                                                                           

  • Access to a file in a jar archive

    Hello.
    I hava a Bean in a jar file. The Bean shoul read a file
    which is is also in the sama archive. The location of the jar file is unknow.
    How can the Bean read the file.
    With friendly regards
    tom

    I (now) know about images in jars...
    //usage: loadIcon("icons/Open16.gif")
         public ImageIcon loadIcon( String location ){
              URL img = null;
              try  {
                   img = ClassLoader.getSystemResource(location);
              }catch (Exception e){
                   e.printStackTrace();
              return new ImageIcon(img);
         }Make sure that the location that you use is case sensitive and the seperator is "/".
    In the usage above, the image is in a dedicated "icons" folder in the jar.

  • Can I refer to a file insider a .JAR archive with an instance of File?

    Hi,
    I was wondering if it is possible to refer to a file stored inside a .JAR file just as if it was on a regular folder by using an instance of the java.io.File class. Otherwise, how can one do that?
    Essencially what I need is to check if a particular class file is contained inside a .JAR archive.
    Best regards,
    Norberto

    http://java.sun.com/j2se/1.4.2/docs/api/java/util/jar/JarFile.html
    See the entries() method to get a list of everything in the jar file. Most of the time the only thing you would want to do with a File is read the bytes from it, which you can do easily using the JarFile class.

  • Creating a JAR in Eclipse...can't access files in the JAR properly.

    Hi all! I'm a newbie at JAR creation, and am having troubles. I have a project that loads images from image files in my project. I can create the JAR and all, and it runs, but the buttons that have ImageIcons with those IO loaded images are blank. I've tried to include the images when creating the JAR, but it keeps acting like the images never existed. When I run the JAR and have the images separately included in the directory (instead of packing them up too), it won't work as well...UNLESS those images are put in my $HOME directory (Linux).
    Does anyone know how I can properly refer to the images that I'm trying to pack into the JAR from within the JAR? Or, is there a way for the JAR to understand where those images are supposed to be (redirect the focus from the $HOME directory to the JAR's directory)? Any help would be greatly appreciated! :)
    -Keith

    Hi,
    Can the user execute the program through explorer? In Windows Server 2003, the Users group does not have Read and Execute permissions to the command processor (Cmd.exe). 
    You could refer to the article below to resolve the issue:
    "Access is denied" error message when you run a batch job on a Windows Server 2003-based computer
    http://support.microsoft.com/kb/867466
    Best Regards,
    Mandy 
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • Create a jar file using the jar tool

    Hello all,
    can somebody help me with this situation:
    I use the following comand
    jar cfm Seti.jar manifest.mf SetiSeti.jar is the name of the file I want to create and Seti is the name of the folder where I have the class files, the manifest file and the Seti.java. The manifest file is also out of this folder (exactly the folder were I use the command on the command line).
    After creating the jar... I try to run it but it gives an error message: "can't find the main class..."
    The content of the manifest file is:
    "Manifest-Version: 1.0
    Main-Class: Seti
    I'd never created a jar file before and have already read all the usefull information here and at sun... I'm very preoccupied with this..
    Can you help?
    Thanks

    RuiAranhaJava wrote:
    How do I do this?
    "And you have to name that package as well when you name the main class in the manifest. "
    But, as I have told the name of the package is SetiNo, you just told us that the name of your class is Set. You never told us about the name of the package.
    Simples question possible: Does your class look something like this:
    package Seti;
    // maybe there are some import statements here, maybe not
    public class Seti {
      // maybe there's something here, maybe not
      public static void main(String[] args) {
        // anything
    }If so, then the fully qualified name of your class is "Seti.Seti" and you need to write that into the Main-Class attribute. (*)
    If there is no package-Statement, then the fully qualified name of your class is simply "Seti" and the Main-Class attribute is correct, but your classes are in the wrong place.
    Edit:
    (*) Please note that package names should generally be all-lowercase, so it should be "seti" instead of "Seti". This helps distinguish it from the simple names of classes, so it's easy to see what you are talking about at a glance: "seti" would be the package, "Seti" the class name.

  • How to modify files in the jar pack

    Is there any way to allow the classes to read and write the files or directories which are inside the same jar file?
    Thanks

    I think you can consider the jar file as a zip file and modify the content of it using
    java.util.zip package:
    http://www.java-tips.org/java-se-tips/java.util.zip/

Maybe you are looking for

  • Automatically closing statements

    Hi. Is there a way to automatically close all statements and ResultSets associated with a Connection if all you have is the Connection? (without closing the Connection) Thanks.

  • Simple AS3 question

    in AS2 I used to load swf and send vars to the swf through the url like that: _root.loadMovie("myMovie.swf?name='bob'") how would i do it in As3 thanks

  • Flickering Flash Logo in page header

    Hey, I am pretty sure that I am not going to be able to prevent this: anybody figured out yet how to keep a Flash log from flickering and disappearing/reappearing when you pull down a drop down menu? Doesn't look like Adobe has, either, their nav bar

  • How Install IE 11 in Windows 8.0

    Hello I have IE 10 in windows 8 pro, but I was surfing to the internet and I didn't find a link with IE 11 for Windows 8. It´s posible to install IE 11 in windows 8.

  • Firefox cannot load multiple webpages at once, especially apps without crashing.

    Firefox doesn't load webpages, especially when tabs are pinned. It cannot connect to more than one site at a time, especially if pandora is playing. Instead of crashing, all I see is spinning gray circles. Also, startup is the worst, I cannot get 4 p