Results 1 to 4 of 4
- 05-12-2011, 05:20 PM #1
Member
- Join Date
- May 2011
- Posts
- 2
- Rep Power
- 0
Reading text from files in package
Ok so I have a problem, its pretty annoying too. I want it so that when my program starts up, one of the first things that is done is that a String will be created and initialized to the contents of a text file in my package.
I am using Netbeans 7.0 to create the program and perhaps my use of terminology is incorrect when I say package. By package I mean the text file is in the same folder as my .java files that are inside the folder contained in the 'src' folder which is in the project folder (ie C:\.....<project name>\src\<folder name>\myText.txt). In my case it the names follow C:\.....MyProject\src\MyPackage
Heres a snippet of my method that deals with the reading from text part where PC is the name of my main class and 'dir' is the String "/myPackage/myText.txt":
Now when I run the program and check to see if it works, its fine. My String is indeed the contents of the text file I wanted to read from. The problem I have is that when I click "Clean and Build" to make it into a .jar file. When I run the .jar, the file is no longer read correctly.Java Code:public static String stringFromFile(String dir) { String s = ""; File file = new File(dir); try { file = new File(PC.class.getResource(dir).toURI()); } catch (Exception e) {} // Deal with reading line by line adding each line to s return s; }
I can confirm the problem is with the lineand not surprisingly, this is the one line that I basically copy/pasted off the internet without really understanding how it works. My understanding is that it checks the directory of the PC class and then searches the 'dir' within that directory.Java Code:file = new File(PC.class.getResource(dir).toURI());
So what needs to be done so that after creating the .jar file, It will still read myText.txt without problems?Last edited by Corpsecreate; 05-12-2011 at 05:22 PM.
-
jars don't have files but rather resources. use the resource to initialize a stream and read from the stream.
- 05-12-2011, 05:43 PM #3
Member
- Join Date
- May 2011
- Posts
- 2
- Rep Power
- 0
Ok I changed it around to use .getResourceAsStream and everything works fine now. Thank you so much Fubarable. I really need to learn how this i/o stuff works.
-
Similar Threads
-
Reading Text Files
By javaman1 in forum New To JavaReplies: 3Last Post: 02-27-2011, 02:13 AM -
Reading raw text files
By DrSaturn in forum AndroidReplies: 0Last Post: 02-24-2011, 07:07 PM -
Reading text files
By SuitMyPants in forum Advanced JavaReplies: 2Last Post: 09-27-2010, 05:14 PM -
Reading text files
By SuitMyPants in forum New To JavaReplies: 2Last Post: 09-27-2010, 02:39 PM -
Reading In Text Files
By Dukey in forum New To JavaReplies: 4Last Post: 04-04-2009, 11:53 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks