0

I want to say I search a lot even google and stackoverflow. There are many topics about this but I dont find exactly what I need.

My problem is :

I want to define file which is in my own package folder.File's format is .txt. And file is in xxx\src\xxxx\myTXTFile.txt I write this code to reach my txt:

  File f = new File(xxx.class.getResource("pr.txt").getFile());

When I run this code on netbeans yes it works.But when I compile and click .jar file it reports:

File not found 

What can I do?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user1716182
  • 51
  • 1
  • 9
  • Are you sure that the files is available in your jar file? check you jar file and make sure the file is there – mhshams Nov 26 '12 at 07:50
  • sorry what do you mean i dont understand? The txt file in my classes folder. src/xxx/ inhere – user1716182 Nov 26 '12 at 07:54
  • 1
    Clicking "jar" generates a jar file, which is basically a zip file. Figure out where this file is, Unzip it, and look for your .txt file. If it isn't there, figure out how to get NetBeans to include the .txt file in the jar it is generating. – Cory Kendall Nov 26 '12 at 07:56
  • Or, rather than unzipping it, you can run `jar -xvf myJarFile.jar` from the command line. – Cory Kendall Nov 26 '12 at 07:57
  • I check it and I see the my txt file.it is there – user1716182 Nov 26 '12 at 08:05

2 Answers2

1

You can reach your txt-File with this code:

File f = new File("xxxx/myTXTFile.txt");

or you must save your txtfile in a Tempfolder:

        InputStream is = getClass().getClassLoader().getResourceAsStream("xxxx/myTXTFile.txt");
        OutputStream os = new FileOutputStream(new File("/tmp/tempTXTFile.txt"));

        while ((i = is.read(buffer)) != -1)
        {
            output.write(buffer, 0, i);
        }

        output.close();

        is.close();

        File f = new File("/tmp/tempTXTFile.txt");
phoenix
  • 49
  • 7
1

In the IDE the file still resides also outside the zip-format jar. Hence was found. For files inside the jar use:

OutputStream f = xxx.class.getResourceAsStream("pr.txt");

File does not work.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • I need file. It is impossible? – user1716182 Nov 26 '12 at 08:23
  • Yes impossible, File represents a OS file; but the next java will see a generalisations of many programmatic file systems, like the zip file system. The solution of @phoenix copies this resource to a temporary file, and uses that. You could use [File.createTempFile](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String) for that. – Joop Eggen Nov 26 '12 at 08:38
  • The OutputStream is more generic: for any File usage, one could always use `new FileOutputStream(file)`. – Joop Eggen Nov 26 '12 at 08:41