*.txt Files in *.Jar

Hi!
In my project I have both Images and txt files that needs to follow the jar. I have no problem getting the images to work using this example: http://www.devx.com/tips/Tip/5697
URL myurl = this.getClass().getResource("png/1.png");
Toolkit tk = this.getToolkit();
Image img = tk.getImage(myurl);I have not been able to find out how to get this to work with txt files. In my project the txt is opened using a string like this:
File file = new File("src/myProject/txt/"+ "File.txt");This works fine when using netbeans, but the file is not opened when running the program from the jar
I noticed that Toolkit does not have a getFile( URL url ), is there a similar way to do this? How do I create File objects in a jar?
Thanks in advance!
Edited by: ja9unath on Dec 2, 2009 7:16 AM
Edited by: ja9unath on Dec 2, 2009 7:16 AM

>
Why do you need to? You can read an InputStream or use it to create an InputStreamReader.
I don't know if it will work, but you can try to convert the URL to a URI and File has a constructor that takes an URI.I have found no method to convert URL 2 URI. Is there such a thing?
I need to use a File-object since I am using this method in my project:
public String txt2String(File file) {
        String output;
        StringBuffer contents = new StringBuffer();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;
            // repeat until all lines is read
            while ((text = reader.readLine()) != null) {
                contents.append(text).append(System.getProperty(
                        "line.separator"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
        output = contents.toString();
        return output;
    }so... How to create a File-object from the *.jar? or is there a way to make this method use InputStream instead of File?
Thanks

Similar Messages

  • Retrieving .txt file from jar for an applet

    I guess this is a newbie question but i checked the tutorial sessions and i am doing exactly what it says there but still...no luck:
    I'm trying to access a .txt. file stored in the .jar file where my applet .class file is stored. I'm using:
    String s = "myfile.txt";
    // get current Class loader
    ClassLoader cl = this.getClass().getClassLoader();
    FileInputStream is = new FileInputStream((cl.getResource(s)).toString());
    BufferedReader in = new BufferedReader(new InputStreamReader(is));But when the applet is viewer from the browser or from the appletviewer, i'm getting the FileNotFoundException:
    java.io.FileNotFoundException: jar:file:\C:\FeatureSelection\sFeatureSelection.jar!\myfile.txt (The filename, directory name, or volume label syntax is incorrect)
    I tried to use the following instead:
    FileInputStream is = new FileInputStream((myApplet.class.getResource(s)).toString());orFileInputStream is = new FileInputStream((getClass().getResource(s)).toString());but the same exception is still there.
    The jar file and the html file are all stored in this directory C:\FeatureSelection\
    The signed jar file is called sFeatureSelection.jar
    Any help would be greatly appreciated!
    Thanks.

    One way to get at files in a jar is to put the jar in the CLASSPATH and then just refer to the resource by its path in the jar. If the same path occurs in two different jars, then you only get the first one, based on the order of the jars in CLASSPATH, I think.
    The classloader is involved, which can be confusing, but an easy way to try this is:
    String s = "myfile.txt";
    URL u = this.class.getClassLoader().getResource(s);
    Object o = u.getContent();Now, you only really know that something matched that path and now it is in a URL.
    I think the Object will be a stream and you have to read() it or something.
    BTW: I encourage you to examine the URL, but it is not necessary to do so.
    If you have somehitng like a GIF image, then here is an example of how to work with that:
    http://www.devx.com/tips/Tip/5697
    Here is a way to get the bytes without involved the ClassLoader:
    http://www.javaworld.com/javaworld/javatips/jw-javatip49.html
    Take your pick.

  • Retrieving .txt file from JAR

    I guess this is a newbie question but i checked the tutorial sessions and i am doing exactly what it says there but still...no luck:
    I'm trying to access a .txt. file stored in the .jar file where my applet .class file is stored. I'm using:
    String s = "myfile.txt";
    // get current Class loader
    ClassLoader cl = this.getClass().getClassLoader();
    FileInputStream is = new FileInputStream((cl.getResource(s)).toString());
    BufferedReader in = new BufferedReader(new InputStreamReader(is));But when the applet is viewed from the browser or from the appletviewer, i'm getting the FileNotFoundException:
    java.io.FileNotFoundException: jar:file:\C:\FeatureSelection\sFeatureSelection.jar!\myfile.txt (The filename, directory name, or volume label syntax is incorrect)
    I tried to use the following instead:
    FileInputStream is = new FileInputStream((myApplet.class.getResource(s)).toString());orFileInputStream is = new FileInputStream((getClass().getResource(s)).toString());but the same exception is still there.
    The jar file and the html file are all stored in this directory C:\FeatureSelection\
    The signed jar file is called sFeatureSelection.jar
    Any help would be greatly appreciated!
    Thanks.

    Thanks for your help, but i'm still getting the same exception:
    java.io.FileNotFoundException: file:\c:\FeatureSelection\sFeatureSelection.jar!\myfile.txt (The filename, directory name, or volume label syntax is incorrect).
    As for the JarInputStream, i checked it out online, but i'm not too sure how i can use these methods to apply'em for my problem here. Does anyone have a sample code that uses JarInputStream?
    Thanks.

  • How to use txt files in jar file

    Hi all
    I just made a program that uses a text file, but I havent managed to work it correctly, program runs without jar correctly, but when I packaged all files into a jar, it couldnt find txt file, so I can only run it when I create another text file outside of jar.
    How can I solve this??

    I used this:
    Scanner fileScan = new Scanner (new file
    ("Words.txt"));
    but when I make a jar file, it doesnt find the txt
    file inside a jar,
    do I need to specify path or something?I have already told you that you shouldn't use new File(..) you should use getResourceAsStream(String name) to get an InputStream to the file.
    Kaj

  • Can I store .txt files in a jar and read them?

    I have searched the forum and didn't find exactly what I needed.
    I have multiple .txt files that will most likely not change over time. I have a class that reads them as needed. I need to do this in a jar file but can not seem to read the .txt files.
    Any help?

    You should be able to read them using an idiom like this:
    URL textURL = MyClass.class.getResource("res/txt/TextResourceFile.txt");where MyClass is the name of a class, and the specified path is relative to the location of that class.
    I haven't actually tried this for text files, but I do use it to load images, so it ought to work for this too.

  • Security restrictions , how to read access a txt file supplied in a jar

    I had written a simple application which uses file handling to display random line from a file on a swing window
    but I do not know how to give my web application permission to access a file
    when I set security permission to all, then error says the application cannot load because the code require unrestricted acess to system resources and is unsigned, I don't know how to get that certificate and I am only doing it for learning purposes.
    when I remove security permissions then it says
    access denied java.io.FilePermissions geekjoskes.txt readPlease help
    I locally signed the jar file, and give my jnlp fiel all permissions, worked fine in my system but when I access same file from local lan it sho errors ,
    please help, I have my txt file stored in my jar file with main class
    the whole jnlp file is
    <?xml version="1.0" encoding="utf-8"?>
    <!-- JNLP File for geek jokes -->     
    <jnlp spec="1.0+"
           codebase="http://localhost/javasoft/webstart/"
          href="geekjokes.jnlp">
       <information>
          <title>Geek Jokes</title>
          <vendor>Vaibhav Mishra</vendor>
          <description>Geeky jokes</description>
          <homepage href="http://scjpbeginner.blogspot.com"/>
          <description kind="short">shows random jokes</description>
          <offline-allowed/>
       </information>
       <resources>    
            <jar href="GeekJokes0.1.jar"/>  
         <j2se version="1.6+"
               href="http://java.sun.com/products/autodl/j2se"/>
         <icon href="geekjokes.gif"/>
       <icon kind="splash" href = "geekjokes.gif"/>
       </resources>
       <security>
          <all-permissions/>
       </security>
       <offline-allowed/>  
       <application-desc main-class="GeekJokes"/>
    </jnlp>Edited by: 76jsr on Aug 7, 2008 3:45 PM
    Edited by: 76jsr on Aug 7, 2008 3:49 PM

    >
    I am extremely thankful to you and finally my first little app is working thanks to you,
    here is it's link
    [http://profile.iiita.ac.in/IIT2006117/javasoft/webstart/geekjokes/geekjokes.jnlp|http://profile.iiita.ac.in/IIT2006117/javasoft/webstart/geekjokes/geekjokes.jnlp] >
    I am glad you got it working! But that launch file is still slightly invalid.
    Here is a corrected, and slightly optimized (you can leave the prefix off the href, if it is the same as the codebase), version of it.
    <?xml version="1.0" encoding="utf-8"?>
    <!-- JNLP File for GeekJokes 0.3 app -->
    <jnlp spec="1.0+"
          codebase="http://profile.iiita.ac.in/IIT2006117/javasoft/webstart/geekjokes"
          href="geekjokes.jnlp">
       <information>
          <title>GeekJokes App</title>
          <vendor>Vaibhav Mishra</vendor>
          <homepage href="http://scjpbeginner.blogspot.com"/>
          <description>Geeky Jokes</description>
          <description kind="short">Cshows random jokes</description>
          <offline-allowed/>
       </information>
       <resources>
           <j2se version="1.6+"
               href="http://java.sun.com/products/autodl/j2se"/>
           <jar href="GeekJokes0.3.jar"/>
       </resources>
       <application-desc main-class="Process"/>
    </jnlp>Very 'Geeky', BTW. ;-)
    Another few things I noted when I looked at it.
    1) There is a stray thread going after the JOptionPane is dismissed. The VM does not end, and the console (if you have it configured to pop-up for JWS apps.) stays on-screen.
    2) If all the jokes are prefixed by '* ' I would recommend removing it from every line of the source file and either re-adding it at runtime, or (preferably) not adding it at all (since it is redundant).
    3) Reconfigure the app. into a loop, and offer the user a JOptionPane with "Another Joke"/"End" instead of "OK".
    4) You can always remove that debugging line I inserted in the code to show the path to the Jar - it was just intended as a 'sanity check' during testing.
    5) Why is it Java 1.6+? JOptionPane was introduced in Java 1.2 with the first Swing implementations, and the I/O is compatible with Java 1.1.
    >
    Thanks again!!!!>Thanks are best expressed (to me) in the notation of a helpful/correct answer (which you have done), and the assignation of (the remaining) dukes*. ;-)
    * After all - checks the title - we have gotten entirely around those 'security restrictions' in a sandboxed application. The reason being that File objects are rarely the correct choice, for applets or JWS apps.

  • Read a txt file when I run jar file

    Hi all,
    I have a jar file. In ir there are:
    /file.jar
       |----/pack
       |        |----MyClass.class
       |        |----file.txt
       |
       |----/META-INF
       |        |----MANIFEST.MFI want: when I execute the jar file java -jar file.jar from the java class MyClass to read the file.txt
    When I run this the error is:
    C:\Documents and Settings\pc\Escritorio>java -jar file.jar
    java.io.FileNotFoundException: file:\C:\Documents%20and%20Settings\pc\Escritorio\file.jar!\pack\file.txt (El nombre de archivo, directo
    rio o etiqueta del volumen no es valido)
            at java.io.FileInputStream.open(Native Method)
            at java.io.FileInputStream.<init>(Unknown Source)
            at java.io.FileInputStream.<init>(Unknown Source)
            at java.io.FileReader.<init>(Unknown Source)
            at pack.MyClass.main(MyClass.java:20)
    Exception in thread "main" java.lang.NullPointerException
            at pack.MyClass.main(MyClass.java:31)the code into the java class is:
    package pack;
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStream;
    public class MyClass {
         private static String version = null;
         static String fich = "file.txt";
         public static void main(String[] args) {
              BufferedReader br = null;
              File file = new File(fich);
              try {
                   br = new BufferedReader(new FileReader(MyClass.class.getClass().getResource("/pack/file.txt").getPath()));
                   String j= null;
                   while ((j = br.readLine())!=null){
                        version = j;
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
              } catch (IOException io){
                   io.printStackTrace();
              } finally{
                   try {
                        br.close();
                   } catch (IOException e) {
                        e.printStackTrace();
              if (version != null)
                   System.out.println("I have read : "+version);
    }in MANIFEST.MF file:
    Manifest-Version: 1.0
    Main-Class: pack.MYClassthanks very much

    thanks you!!
    I have read the file, but I have put the package when I write the file.txt, beacuse If I don't put this, givas me NullPointerException
    Now I have
    InputStream in = Main.class.getResourceAsStream("/pack/file.txt");
    InputStreamReader isr = null;
    BufferedReader reader = null;
    try {
              isr = new InputStreamReader(in, "ISO-8859-1");
              reader = new BufferedReader(isr);
              while ((j = reader.readLine())!=null){
                   version = j;
              reader.close();
    } catch ...Thanks very much

  • Reading .txt file on Windows Server 2008

    I have a Java 7 application that we distribute, and it reads configurations from a .txt file distributed with it, in the same directory as the .jar file. On Windows 7, windows XP, Windows 8, this works fine, but on our server, running Windows Server 2008, this fails. It is a simple check that fails:
    Path p = Paths.get("config.txt");
    if(Files.isReadable(p))
    This will not work on Windows Server 2008 r2. It suspect that it somehow hasn't got read permissions, but I'm not sure.
    It also fails if the absolute path is specified.

    And what if you use the regular old fashioned standard IO File class and not Files to check if the file is readable (File.canRead())?
    Methinks (or to be honest: I guess) there is something odd with the creation of the Path object on your windows server file system, but I wouldn't be able to tell what exactly.

  • "componentRequest, aResponse" variables in logon_proxy.txt file issue

    Hi All,
    We are  upgraded portal to Netweaver 7.0 to 7.3  version. Par files are no longer supported. So, we converted par files to ear file. When I open ear file in eclipse IDE for Java developers, initially some jar files are missing in ear file. I added Jar files. But when we are calling logon_proxy.txt file in jsp pages(changePasswordPage.jsp, umLogonPage.jsp,...) proxy, inportal, webpath varaibles (which defined in logon_proxy.txt file) are not declared error raising.
    please suggest me.
    Thanks
    Srinivas

    Hi All,
    We are  upgraded portal to Netweaver 7.0 to 7.3  version. Par files are no longer supported. So, we converted par files to ear file. When I open ear file in eclipse IDE for Java developers, initially some jar files are missing in ear file. I added Jar files. But when we are calling logon_proxy.txt file in jsp pages(changePasswordPage.jsp, umLogonPage.jsp,...) proxy, inportal, webpath varaibles (which defined in logon_proxy.txt file) are not declared error raising.
    please suggest me.
    Thanks
    Srinivas

  • Read txt files in DoJa?

    I don't know if this is the right place to post this, but I haven't found any DoJa topic neither have I found good DoJa forums. So I thought I post it here.
    My problem is: I'm trying to read and write .txt files in DoJa. I've wrote this script in JCreator (with other imports ofcourse), and it worked perfectly. But as I already expected it won't work in javaaplitool (2.5):
    import com.nttdocomo.io.*;
    import com.nttdocomo.ui.*;
    class ReadFile
    void ReadMyFile()
    DataInputStream data_input_stream = null;
    String input = null;
    try
    File file = new File("testfile.txt");
    FileInputStream input_stream = new FileInputStream(file);
    BufferedInputStream buffered_input_stream = new BufferedInputStream(input_stream);
    data_input_stream = new DataInputStream(buffered_input_stream);
    while ((input=data_input_stream.readLine()) != null)
    System.out.println(input);
    I've tried other things but it won't do and I'm not an expert in this :-(. Anyone know how to do it or have a small sample script or anything that can help?
    Any help is greatly appreciated!

    You're not doing it correctly. Use getClass().getResourceAsStream("yourtext.txt") to read data. Note that you cant just read files on phones, Java runs in a sandbox and only has access to files includes in tje Midlet JAR.

  • Unwanted txt files in dektop

    Please Help.
    Every time I save a file in the desktop folder (for example a MS Word file), the system automatically saves an infinte number of TXT files in the same desktop. The amount of TXT files goes in direct proportion to the size of the files saved... this means that with large files, the computer gets beach balls saving all those TXT files....
    This happens with any file type
    any ideas?

    >
    Why do you need to? You can read an InputStream or use it to create an InputStreamReader.
    I don't know if it will work, but you can try to convert the URL to a URI and File has a constructor that takes an URI.I have found no method to convert URL 2 URI. Is there such a thing?
    I need to use a File-object since I am using this method in my project:
    public String txt2String(File file) {
            String output;
            StringBuffer contents = new StringBuffer();
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(file));
                String text = null;
                // repeat until all lines is read
                while ((text = reader.readLine()) != null) {
                    contents.append(text).append(System.getProperty(
                            "line.separator"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (reader != null) {
                        reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
            output = contents.toString();
            return output;
        }so... How to create a File-object from the *.jar? or is there a way to make this method use InputStream instead of File?
    Thanks

  • Pb with file in jar

    I develop a small app which need to read information on text file in the Jar. The Emulation in Eclipse works well but when I use netbeans to make easily the Jar I have a problem and the program is unable to connect to the file.
    Where must I stock the file in the Jar? (In netbeans the .txt file where stock in <default package>.

              The request is in the form of multipart data and is parsed by the
              Oreilly class only. To access other information from the request
              the Oreilly class has provided you with the methods for getting
              the other data. You have to access the data from the request using
              the Oreilly class methods
              "Cameron Purdy" <[email protected]> wrote:
              >Be careful what methods you call on the request object.
              > They can prevent
              >you from later asking for that all-important input stream.
              >
              >--
              >Cameron Purdy
              >Tangosol, Inc.
              >http://www.tangosol.com
              >+1.617.623.5782
              >WebLogic Consulting Available
              >
              >
              >"Laurent Andre" <[email protected]> wrote
              >in message
              >news:3a88184c$[email protected]..
              >>
              >> Hello,
              >>
              >> we do have a problem with file upload ! We're using
              >the o'reilly class,
              >but every
              >> time we add ENCTYPE="multipart/formdata" in the html,
              >we're unable to
              >correctly get
              >> the request. ?
              >> any idea ? Is there something to configure ?
              >>
              >> thx
              >>
              >
              >
              

  • Read a txt file from MIDlet

    dear sir,
    I am working on a midlet which should read position information (privided by TOMTOM GPS) from a TXT file and send it to a server.
    In Toolkit everything works fine, but when I transfered the midlet on a ipaq pocket pc running windows and using IBM j9 jvm I got problems.
    I can not read any file which is not in the package of the MIDlet
    here is the code:
    //read position from textfile
    try {
    Class c = this.getClass();
    InputStream is = c.getResourceAsStream("iamhere.txt");
    StringBuffer str = new StringBuffer();
    byte b[] = new byte[1];
    while ( is.read(b) != -1 ) {
    str.append(new String(b));
    is.close();
    position = str.toString();
    catch (Exception e) {
    e.printStackTrace();
    position = new String("Sorry: I can not read position of your friend!");
    can it be that this operation is generally not allowed or that the path is not correct (i tryed also file:///java/iamhere.txt)
    thanks for any help
    dominik

    hi,
    this works fo me:
    download ibm websphere trail from IBM website.
    install websphere andwebsphere everyplace on the pocket pc
    in the websphere program there is a update tool
    launch it and download and install fileconn.dll pimdll.dll
    (I do not remember how it is called but something like jsr 75 or fileconnector or fc)
    � Copy E:\WSDD\wsdd5.0\ive-2.2\runtimes\wm2003\arm\midp20\bin\j9.exe to
    \Program Files\J9\MIDP20\bin\
    � Copy
    E:\WSDD\wsdd5.0\ive-2.2\runtimes\wm2003\arm\midp20\bin\fileconn.dll to
    \Program Files\J9\MIDP20\bin\
    � Copy E:\WSDD\wsdd5.0\ive-2.2\runtimes\wm2003\arm\midp20\bin\pimdll.dll
    to \Program Files\J9\MIDP20\bin\
    � Copy jars from
    E:\WSDD\wsdd5.0\ive-2.2\runtimes\wm2003\arm\midp20\lib\jclMidp20\ext\ to
    \Program Files\J9\MIDP20\lib\jclMidp20\ext\
    and in the JAD:
    MIDlet-Permissions:
    javax.microedition.io.file.read,javax.microedition.io.file.write
    hope this helps.
    Ciao

  • Txt file missing after deploying war

    All,
    i've encountered weird problem when i'm deploy new war to the server. i want my class read the txt file. so that i've put the txt file at the same path as class as well at src/javapackage. here is the path..
    F:/myapp/voip/src/clientpkg
    so that i assumed when i deploy the war file to the server all classess & txt file will be kept at the ...
    webapps/voip/WEB-INF/classes/clientpkg/
    but when i checked at the clientpkg directory, the txt file is missing. what shud i do now?
    here is my code to read the txt file..
    private boolean migration25Cpes() throws Exception {
    boolean status = false;
    try {
    System.out.println(System.getProperty("user.dir"));
    System.out.println("read the file again/");
    InputStream in = this.getClass().getResourceAsStream("list25cpe.txt");
    Reader rin = new InputStreamReader(in);
    BufferedReader inputFile = new BufferedReader(rin);
    String readSource = "";
    while ( (readSource = inputFile.readLine()) != null) {
    System.out.println(readSource);
    System.out.println("the input now : " +inputFile.read());
    inputFile.close();
    catch (FileNotFoundException e) {
    e.printStackTrace();
    return status;
    }

    Then you have to find a way to tell JBuilder to include the text file in the jar. I don't know JBuilder, but I'm guessing that right now it is probably building the jar from the compiler output directory, which contains only class files.
    There may be a setting to copy non-java files to the compiler output directory, or you may need to put stuff you want to appear in WEB-INF/classes in some other location for it to be picked up by the JBuilder war-creator.

  • Reading/getting external .txt files

    Hi,
    I want to display the content of a .txt files (which is located in the src folder) inside a TextBox (or ChoiceGroup, or Form). How do I do this yea? For instance, the TextBox constructor is TextBox(String title, String text, int maxSize, int constraints) rite, how do I fit in the file reading function or value that I get from reading the .txt file into it yea?
    Thanx!

    what do u mean by build the .txt file into the jar?{color:#0000ff}http://java.sun.com/docs/books/tutorial/deployment/jar/index.html{color}
    i tried the examples from ... ...In future, please do not post on long-dead threads. One of those threads you posted on was from 2002.
    Reviewing your initial post and the silly question about the TextBox constructor, I think you are not quite ready for this task. You need to go back to basics and learn the Java language. The Sun Java Tutorials are a good place to start.
    This comment is not meant to discourage you, it is a statement of fact. A good foundation is a must for any developer, or indeed in any sphere of activity.
    db

Maybe you are looking for

  • Bass Drops Out On iTunes CDs

    I have been burning mp3 CDs with iTunes for playback in my car equipped with an mp3 disc player and subwoofer. I noticed the bass was very noticeably dropping-out on nearly all mp3 selections. I thought it was my subwoofer until a bought a new car an

  • Photo continually is downloading for 3 months

    My iPhone 5s is has been downloading for 3months it appears that when I changed phones that it is stuck on downloading picture from the cloud

  • Safari opens with old tabs on start up

    Safari keeps opening with old tabs from about 3 weeks ago rather than my home page. On start up safari is showing as open and there is a folder in the right hand part of the dock. This has the old tabs in it and safari opens with these and not my hom

  • Error Code message A12E1

    What is Error code: A12E1 when trying to download Adobe Application mgr?

  • How to install Adobe reader on this machine

    Is adobe reader installed on this machine?