Reading a text file in my .jar - java

Lets say I'm making a program that needs to copy all the lines in a .txt file within my .jar file. it is in the package program.files and it is named text.txt. I've been looking all over the internet, and i cant find what I'm looking for. i think that this idea:
public String readSpecificFromJar(String dir, int line) {
String read = null;
try {
InputStream in = getClass().getResourceAsStream(dir);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
/**
* declare string variable and prime the read
*/
read = bufferedReader.readLine();
for (int i = 1; i < line; i++) {
read = bufferedReader.readLine();
}
bufferedReader.close();
} catch (IOException ioexception) {
Dialogs.fail("Could not read txt file from the JAR!!! Error Code: 06");
}
return read;
}
would work, but i tried that and it gave me all kinds of errors. what i think the problem would be is declaring the InputStream in the way it does it want the file to be right there with the Main method. how would i change this so it is not the case? thanks in advance!
EDIT:
due to some confusion, i want to clear this up. for the String dir i am entering files/text.txt. it wont work. how do i fix this?
EDIT 2:
OK i feel like the problem isn't getting across, and I'm kinda getting aggravated, mainly because I'm pretty tired. the code that WORKS for a different program is up above, where the dir is simply "text.txt"
THIS DOESN'T WORK FOR WHAT I'M DOING AND IM NOT SURE WHY. again, the file is IN THE CLASSPATH so dir is only "text.txt". I want my .txt file to be "files/text.txt". How do i do this?
EDIT 3:
I dont know if i mentioned it, but my .txt file is INSIDE my jar. just to clear up the confusion. so really, the path of the .jar file shouldn't matter, as in I shouldn't have to type it in with the dir. also, the main class is in the package main and the .txt file is in the package files all within the same program named copy. also, i tried moving the txt file to the same package as the main class, also didn't work.
EDIT 4:
by the way, the package that holds the method for reading from the jar is IO. as in the class io is inside the package IO. all of my files such as images and txt are in the package files. just thought id clear that up. i tried moving the txt file to the package of the io class, and that worked, but if its in any other package, even if i include the package name in the dir it wont work. any ideas as to why?

The .txt file should be in The root directory of dir is the same directory where your class file is located in.
EDIT: due to some confusion, i want to clear this up. for the String
dir i am entering files/text.txt. it wont work. how do i fix this?
What is the path of the class? (the class that contains readSpecificFromJar()) If the .class file and the .txt file are both in the same directory, then you should make it like this:
dir = "text.txt";
EDIT 4: by the way, the package that holds the method for reading from
the jar is IO. as in the class io is inside the package IO. all of my
files such as images and txt are in the package files. just thought id
clear that up. i tried moving the txt file to the package of the io
class, and that worked, but if its in any other package, even if i
include the package name in the dir it wont work. any ideas as to why?
Try this:
dir = "../files/text.txt";
I believe this would work if your structure is as follows:
javaApp.jar
|
_____|_____
| |
files IO
| |
| |
text.txt io.class

Related

Java File Reader not finding appropriate file

I am working on a basic game similar to Break Out and I plan to use a text file to store level data on where various objects should be located when a level is rendered onto the screen. Here is the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LevelData {
public LevelData(){
readFile();
}
public void readFile(){
try{
BufferedReader in = new BufferedReader(new FileReader("Levels"));
String str;
while((str = in.readLine()) != null){
process(str);
in.close();
}
}catch (IOException e){
System.out.println("File Does Not Exist");
}
}
private void process(String str){
System.out.println(str);
}
}
This following code, based off of previous research, should access the file "Levels" that is located in the same package as the Java class, but if the program cannot access the file then it should print "File Does Not Exist" to the console. I have created a file called "Levels" that is located in the same package as the Java class but whenever I run this class, it does not read the file properly and it catches the Exception.
Does anyone have any ideas on why it cannot access the proper file? I have already looked on various other threads and have found nothing so far that could help me.
Thanks in advance
Your Levels file probably doesn't want to be in the same package as the class, but rather, in the same directory from where your java program was run.
If you're using eclipse, this is probably the project directory.
Your issue is probably the lack of a file extension!
BufferedReader in = new BufferedReader(new FileReader("Levels.txt"));
In case you are running from Eclipse, the file should be accessed like new FileReader("src/<package>/Levels") .
Closing the inputstream in.close(); should happen outside the while loop.
As you said you plan to use a text file to store level data. One way to solve the problem is to provide relative path to the file while storing and while reading the file use the relative path to read the file. Please don't forget to specify the extention of the file.
I see a few problems, the first one being there's no file extension. Second, the in.close() is in the while loop, and since you are planning on storing high scores, I would recommend you would use an ArrayList.
It is always a good practice to specify the absolute path name of the file if the file is external to your jar file. If it is part of your jar file, then you need to get it using 'getResourceAsStream()'.

Extracting files from res folder in Executable JAR (txt files to be specific)

I would like to ask if its possible to put text files into my jar, I use them to make my map in my game, but users can get Highscores. now I want to save the Highscores with the map, so I have to save the map on the user their PC. Is there any way how I could do this? I've searched the internet for some ideas but I could not find anything that even came close to what I've wanted. I only had 3/4th of a year java so I don't know much about these things, everything that happens outside the debug of eclipse are problems for me(files are mainly one of those things, null exceptions, etc).
The main question now.
Is it possible to do? If yes, do you have any terms I could search on, or some sites/guides/tutorials? If no, is there any other way how I could save the highscores?
EDIT:
to make clear
Can I get the text file (the text inside the file) to be extracted to a different file in like the home directory of my game (where I save the settings and stuff) the basic maps are inside the jar file, so I want them to be extracted on the first start-up of the program
Greetings Carolien
"extracted to a different file in like the home directory of my game (where i save the settings and stuff) the basic maps are inside the jar file, so i want them to be extracted on the first startup of the program"
You can get the URL by using getClass().getResource()
URL url = getClass().getResource("/res/myfile.txt");
Then create a File object from the URI of the URL
File file = new File(url.toURI());
Then just perform your normal file operations.
if (file.renameTo(new File(System.getProperty("user.home") + "\\" + file.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
Assuming your file structure is like below, it should work fine
ProjectRoot
src
res
myfile.txt
Note: the above is moving the entire file. If you want to extract just the data inside the file, then you can simple use
InputStream is = getClass().getResourceAsStream("/res/myfile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The just do normal IO operation with the reader. See here for help with writing the file.

Write to a .txt file in a package

I would like to write to a .txt file that is inside a package. I can get it to read from the exact location the .txt file is stored but not from inside the package. I'm assuming it is using class loaders but I cannot seem to get it to work.
Here is what I have so far.
public void writeFile(String fileLocation) {
Writer output = null;
File file = new File(fileLocation);
try {
output = new BufferedWriter(new FileWriter(file));
output.append("WRITING TEST");
output.close();
} catch (IOException ex) {
System.out.println("Couldn't write to file.");
}
}
Then I use this in another class to write.
WriteFile writeFile = new WriteFile();
writeFile.writeFile("src/com/game/scores.txt");
I understand that if using class loaders you remove "src/" because that will no longer exist when the program is compiled in a .jar.
It is not possible to write or update a file inside jar. Since jar itself is a file.
Please refer this link.
Write To File Method In JAR
You could use a class in that package to give you the location of the folder.
Try something like
public URL getPackageLocation() {
return getClass().getResource(".");
}
This should give you the location of the folder from which this method is being called from.
From the comments you already know that you cann't write to a file, which resides in a JAR file. At best what you can do, is creating your file, relative to the path where the JAR is located like bellow:
mylocation
|-- my-jar.jar
|-- com
|--game
|--myfile.txt
I would like to write to it to update the scores in my game as the
user goes through the levels.
While it might be possible to write to the JAR file, I don't recommend it for this use case. Just write it somewhere at:
Path userdir = Paths.get(System.getProperty("user.home"), ".myApp", "<my app version>");
You can't write into Jar file. Writing into Jar file is not recommendable. You can write outside the jar file.
Please refer this and this stack overflow question for more details.

Eclipse: how/where to include a text file in a Java project?

I'm using Eclipse (SDK v4.2.2) to develop a Java project (Java SE, v1.6) that currently reads information from external .txt files as part of methods used many times in a single pass. I would like to include these files in my project, making them "native" to make the project independent of external files. I don't know where to add the files into the project or how to add them so they can easily be used by the appropriate method.
Searching on Google has not turned up any solid guidance, nor have I found any similar questions on this site. If someone knows how to do add files and where they should go, I'd greatly appreciate any advice or even a point in the right direction. Also, if any additional information about the code or the .txt files is required, I'll be happy to provide as much detail as possible.
UPDATE 5/20/2013: I've managed to get the text files into the classpath; they're located in a package under a folder called 'resc' (per dharam's advice), which is on the same classpath level as the 'src' folder in which my code is packaged. Now I just need to figure out how to get my code to read these files properly. Specifically, I want to read a selected file into a two-dimensional array, reading line-by-line and splitting each line by a delimiter. Prior to packaging the files directly within the workspace, I used a BufferedReader to do this:
public static List<String[]> fileRead(String d) {
// Initialize File 'f' with path completed by passed-in String 'd'.
File f = new File("<incomplete directory path goes here>" + d);
// Initialize some variables to be used shortly.
String s = null;
List<String> a = new ArrayList<String>();
List<String[]> l = new ArrayList<String[]>();
try {
// Use new BufferedReader 'in' to read in 'f'.
BufferedReader in = new BufferedReader(new FileReader(f));
// Read the first line into String 's'.
s = in.readLine();
// So long as 's' is NOT null...
while(s != null) {
// Split the current line, using semi-colons as delimiters, and store in 'a'.
// Convert 'a' to array 'aSplit', then add 'aSplit' to 'l'.
a = Arrays.asList(s.split("\\s*;\\s*"));
String[] aSplit = a.toArray(new String[2]);
l.add(aSplit);
// Read next line of 'f'.
s = in.readLine();
}
// Once finished, close 'in'.
in.close();
} catch (IOException e) {
// If problems occur during 'try' code, catch exception and include StackTrace.
e.printStackTrace();
}
// Return value of 'l'.
return l;
}
If I decide to use the methods described in the link provided by Pangea (using getResourceAsStream to read in the file as an InputStream), I'm not sure how I would be able to achieve the same results. Would someone be able to help me find a solution on this same question, or should I ask about that issue into a different question to prevent headaches?
You can put them anywhere you wish, but depends on what you want to achieve through putting the file.
A general practice is to create a folder with name resc/resource and put files in it. Include the folder in classpath.
You can store the files within a java package and read them as classpath resources. For e.g. you can add the text files to a java package say com.foo and use this thread to know how to read them: How to really read text file from classpath in Java
This way they are independent of the environment and are co-packaged with code itself.
Add the files in the projects classpath.(you can find the class path of the project by right click the project in eclipse->Build Path->configure build path)
I guess you want an internal .txt file.
Package Explorer => Right Click at your project => New => File . Then text a file name and Finish it.
The path in your code should look like this:
Scanner diskScanner = new Scanner(new File("YourFile"));

How to pass a text file as a argument?

Im trying to write a program to read a text file through args but when i run it, it always says the file can't be found even though i placed it inside the same folder as the main.java that im running.
Does anyone know the solution to my problem or a better way of reading a text file?
Do not use relative paths in java.io.File.
It will become relative to the current working directory which is dependent on the way how you run the application which in turn is not controllable from inside your application. It will only lead to portability trouble. If you run it from inside Eclipse, the path will be relative to /path/to/eclipse/workspace/projectname. If you run it from inside command console, it will be relative to currently opened folder (even though when you run the code by absolute path!). If you run it by doubleclicking the JAR, it will be relative to the root folder of the JAR. If you run it in a webserver, it will be relative to the /path/to/webserver/binaries. Etcetera.
Always use absolute paths in java.io.File, no excuses.
For best portability and less headache with absolute paths, just place the file in a path covered by the runtime classpath (or add its path to the runtime classpath). This way you can get the file by Class#getResource() or its content by Class#getResourceAsStream(). If it's in the same folder (package) as your current class, then it's already in the classpath. To access it, just do:
public MyClass() {
URL url = getClass().getResource("filename.txt");
File file = new File(url.getPath());
InputStream input = new FileInputStream(file);
// ...
}
or
public MyClass() {
InputStream input = getClass().getResourceAsStream("filename.txt");
// ...
}
Try giving an absolute path to the filename.
Also, post the code so that we can see what exactly you're trying.
When you are opening a file with a relative file name in Java (and in general) it opens it relative to the working directory.
you can find the current working directory of your process using
String workindDir = new File(".").getAbsoultePath()
Make sure you are running your program from the correct directory (or change the file name so that it will be relative to where you are running it from).
If you're using Eclipse (or a similar IDE), the problem arises from the fact that your program is run from a few directories above where the actual source is located. Try moving your file up a level or two in the project tree.
Check out this question for more detail.
The simplest solution is to create a new file, then see where the output file is. That is the correct place to put your input file into.
If you put the file and the class working with it under same package can you use this:
Class A {
void readFile (String fileName) {
Url tmp = A.class.getResource (fileName);
// Or Url tmp = this.getClass().getResource (fileName);
File tmpFile = File (tmp);
if (tmpFile.exists())
System.out.print("I found the file.")
}
}
It will help if you read about classloaders.
say I have a text file input.txt which is located on the desktop
and input.txt has the following content
i came
i saw
i left
and below is the java code for reading that text file
public class ReadInputFromTextFile {
public static void main(String[] args) throws Exception
{
File file = new File(
"/Users/viveksingh/desktop/input.txt");
BufferedReader br
= new BufferedReader(new FileReader(file));
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
}
output on the console:
i came
i saw
i left

Categories

Resources