Java - Errors when using .txt files in .jar - java

When I try and load up a .txt file in my code, I get this error:
java.io.FileNotFoundException: file:\C:\Users\Me\Desktop\Program.jar!\test\foo.txt (The filename, directory name, or volume label syntax is incorrect)
My code for loading these files is this:
try {
String path = getClass().getResource(file).getPath();
BufferedReader reader = new BufferedReader(new FileReader(path));
...
} catch(IOException e) {
System.err.println("Could not read file!");
e.printStackTrace();
System.exit(-1);
}
And the string I load into the method is this:
foo.txt
Even though I've checked many times, the file exists in that exact path, yet my program still can't find it. And why is there an exclamation mark at the end of Program.jar? Is it important?
Thank you to anyone who helped answer my questions.

If you launch it out of jar in console, you better access your resource as a InputStream and process it the desired way. When you enter the actual path(especially not relative) - you are trying to get to the file that is INSIDE the jar, which is wrong.
Here's close (pseudo) code for your problem:
InputStream resource = ClassName.class.getResourceAsStream("/test/foo.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(resource));
//do some stuff
resource.close();
reader.close();
The exclamation mark is a separator the JVM uses to note the .jar file in the path.

Related

Ensuring a text file is included in a JAR

My apologies if this is a duplicate, I've been searching around and haven't found anything that works.
I've been trying export a project as a JAR file that includes reading information from a text file. After doing some research, I changed my reader from FileReader to InputStreamReader, using CLASSNAME.class.getClassLoader().getResourceAsStream("textFile.txt"). (I also understand that it should work without the getClassLoader() method involved) However, getResourceAsStream("textFile.txt") returns null, throwing a NullPointerException when I try to read it using a BufferedReader.
From what I've read, this is because my text file isn't actually in the JAR. Yet when I attempt to do so I still get a NullPointerException. I've also tried adding the folder with the files to the build path, but that doesn't work either. I'm not sure how to check if the files are actually in the JAR and, if not, how to get them in the JAR so they can be found and properly read.
For reference, I currently use Eclipse Neon on a MacBook Air and here is my code that tries, but fails, to read the text file:
public static void addStates(String fileName) {
list.clear();
try {
InputStream in = RepAppor.class.getClassLoader().getResourceAsStream("Populations/" + fileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
/*
* NOTE: A Leading slash indicates the absolute root of the directory, which is on my system
* Don't use a leading slash if the root is relative to the directory
*/
String line;
while(!((line = reader.readLine()) == null)) {
list.add(line);
}
reader.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "The file, " + fileName + ", could not be read.", "Error", JOptionPane.ERROR_MESSAGE);
} catch (NullPointerException n) {
JOptionPane.showMessageDialog(null, "Could not find " + fileName + ".\nNull Pointer Exception thrown", "Error", JOptionPane.ERROR_MESSAGE);
}
}
Thank you for your consideration and I appreciate and welcome any feedback you might have.
There are a number of ways to check the contents of a .jar file.
Most IDEs have a “Files” section where you can simply expand a .jar file, as if it were a directory.
If your have the JDK’s bin subdirectory in your execution path, you can use the jar command in a terminal:
jar tf /Users/AaronMoriak/repappor.jar
Every .jar file is actually a zip file with a different extension (and one or more Java-specific special entries). So, any command that handles zip files will work on .jar files.
Since you’re on a Mac, you have access to the Unix unzip command. In a terminal, you can simply do this:
unzip -v /Users/AaronMoriak/repappor.jar
(The -v option means “view but don’t extract.”)
If your .jar file has a lot of entries, you can limit the output of the above command:
unzip -v /Users/AaronMoriak/repappor.jar | grep Populations
Your code comment about a leading slash is not quite correct. However, if you remove the getClassLoader() part, the comment is somewhat more correct:
// Change:
// RepAppor.class.getClassLoader().getResourceAsStream
// to just:
// RepAppor.class.getResourceAsStream
// Expects 'Populations' to be in the same directory as the RepAppor class.
InputStream in = RepAppor.class.getResourceAsStream("Populations/" + fileName);
// Expects 'Populations' to be in the root of the classpath.
InputStream in = RepAppor.class.getResourceAsStream("/Populations/" + fileName);

How to get path of java files including /src/

im Working on a project that can compile/run existing java files in PC.
most of code works pretty well, but im having a problem at getting the path of java files.
here are the problematic codes
void uploadJ() {
System.out.print("Insert File name : "); //ex)HelloWorld.java
FileName = sc.next();
}
void Compile(){
String s = null;
File file = new File(FileName);
String path = file.getAbsolutePath();
try {
Process oProcess = new ProcessBuilder("javac", path).start();
BufferedReader stdError = new BufferedReader(
new InputStreamReader(oProcess.getErrorStream()));
while ((s = stdError.readLine()) != null) {
FileWriter fw = new FileWriter(E_file, true);
fw.write(s);
fw.flush();
fw.close();
}
} catch...
}
For instance, when i put HelloWorld.java as a file name,
the absolute path of the HelloWorld.java should be C:\Users\user\eclipse-
workspace\TermProject\src\HelloWorld.java,
but instead, the result is C:\Users\user\eclipse-
workspace\TermProject\HelloWorld.java.
it misses /src/ so it always ends up with javac: file not found error.
When your application has been compiled, there will be no src directory. This working directory could also be set to anything.
You also can't guarantee that the file you are looking for is an actual file, in the context of a jar file, it isn't.
However, you can load files from the classpath. You can make use of Class#getResourceAsStream(String):
Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class.`.
Finding the file can be accomplished by calling this.getClass().getResourceAsStream("/" + FileName), with the / causing the search to occur from the resource root.
To use this with javac, you'll have to create a temporary file and populate it with the data stream you get from getResourceAsStream.

How do I create a File object in Java w/out using an absolute path name?

This is the path I'm using now:
C:\Users\Sabrina\Documents\NetBeansProjects\TriangleSumRecursion\lab4Data.txt
I tried just using the following:
C:\TriangleSumRecursion\lab4Data.txt
and
TriangleSumRecursion\lab4Data.txt
If I use either of those two Java will say "(The system cannot find the file specified)"...
TriangleSumRecursion is the java package that I'll turn in.
You can import the particular file into the project, and then try using TriangleSumRecursion\lab4Data.txt
You can import the file by right clicking on your project folder from your IDE, and then click on import. Follow the instructions and give the path of your file in it.
i hope it works for you.
First of all, use Slashes ('/'), not Backslashes ('\') in Javacode.
But besides of that, Java can handle absolute and relative paths.
I tried just using the following: C:\TriangleSumRecursion\lab4Data.txt
This is not the right absolute path, if there is no folder 'TriangleSumRecursion' in C:\. Your working path example is the only right one.
and TriangleSumRecursion\lab4Data.txt
Here you try this as a relative path. Java starts its search in the folder your file, running the code, is located. So this would work, if your java file was in 'C:\Users\Sabrina\Documents\NetBeansProjects'.
But since I think your file is in 'TriangleSumRecursion', the path you are looking for is simply 'lab4Data.txt'.
You could try the following reading your file line by line, by first reading the file through a file reader, that is then fed to the buffered reader. Then you can create a string buffer, and as the program reads each line of the file it will append it to the string buffer. To check if it was successful just simply close the file reader and use the toString() method to display the contents of the file.
`public static void main(String[] args) {
try {
File file = new File("lab4Data.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("File is:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}`
C:\TriangleSumRecursion\lab4Data.txt is an absolute path, so this will not identify your file which is not at this location.
You are more than probably in directory C:\Users\Sabrina\Documents\NetBeansProjects\TriangleSumRecursion, therefore a simple:
Paths.get("lab4Data.txt")
will give you a Path to your file (this is 2015; use java.nio.file and drop File).
But this is Windows and there are some strange things with Windows... Another way to access your file would be:
Paths.get("c:lab4data.txt")
Which is a path which has a root (c:) but which is not absolute (since such a path cannot be used to uniquely identify a resource on the FileSystem.
See the Files class on how to open, for instance, an InputStream or a BufferedReader from this file. And note that if the file does not exist the matching methods will throw a NoSuchFileException.
Last but not least, use a try-with-resources statement:
try (
final BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
) {
// use the reader here
}

The system cannot find the file specified in java

I am making a program that opens and reads a file.
This is my code:
import java.io.*;
public class FileRead{
public static void main(String[] args){
try{
File file = new File("hello.txt");
System.out.println(file.getCanonicalPath());
FileInputStream ft = new FileInputStream(file);
DataInputStream in = new DataInputStream(ft);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strline;
while((strline = br.readLine()) != null){
System.out.println(strline);
}
in.close();
}catch(Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
but when I run, I get this error:
C:\Users\User\Documents\Workspace\FileRead\hello.txt
Error: hello.txt (The system cannot find the file specified)
my FileRead.java and hello.txt where in the same directory that can be found in:
C:\Users\User\Documents\Workspace\FileRead
I'm wondering what I am doing wrong?
Try to list all files' names in the directory by calling:
File file = new File(".");
for(String fileNames : file.list()) System.out.println(fileNames);
and see if you will find your files in the list.
I have copied your code and it runs fine.
I suspect you are simply having some problem in the actual file name of hello.txt, or you are running in a wrong directory. Consider verifying by the method suggested by #Eng.Fouad
You need to give the absolute pathname to where the file exists.
File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
In your IDE right click on the file you want to read and choose "copy path"
then paste it into your code.
Note that windows hides the file extension so if you create a text file "myfile.txt" it might be actually saved as "myfile.txt.txt"
Generally, just stating the name of file inside the File constructor means that the file is located in the same directory as the java file. However, when using IDEs like NetBeans and Eclipse i.e. not the case you have to save the file in the project folder directory. So I think checking that will solve your problem.
How are you running the program?
It's not the java file that is being ran but rather the .class file that is created by compiling the java code. You will either need to specify the absolute path like user1420750 says or a relative path to your System.getProperty("user.dir") directory. This should be the working directory or the directory you ran the java command from.
First Create folder same as path which you Specified. after then create File
File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");
if(!file.exists())
{
dir.mkdir();
file.createNewFile();
System.out.println("File,Folder Created.);
}
When you run a jar, your Main class itself becomes args[0] and your filename comes immediately after.
I had the same issue: I could locate my file when provided the absolute path from eclipse (because I was referring to the file as args[0]). Yet when I run the same from jar, it was trying to locate my main class - which is when I got the idea that I should be reading my file from args[1].

Java Method Can't Pick Up Files

I'm writing a Java program that has a working drag and drop GUI for files. All of the files that are dragged in the DnD GUI are put into an String array that holds the file names. I have a method that loops through the array and strips the path to leave only the filenames and then sends the filename (for the Scanner) and the desired output filename (for the PrintWriter) to this method at the end of each loop:
public void fileGenerator(String in, String out) {
try {
String current_directory = System.getProperty("user.dir");
Scanner input = new Scanner(new FileReader(current_directory+"/"+in));
PrintWriter output = new PrintWriter(current_directory+"/"+out);
while(input.hasNext()) {
String line = input.nextLine();
output.println(line);
} output.close();
input.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
The code is not working, it does not produce the output file. I am getting a "No such file or directory" error with the full path... I have tested it in terminal, it is the correct path. Any input is appreciated.
I should note that all of the Java source files, classes, and input files are in the same directory.
Thanks!
First problem I see is that you ignore the exception, so you don't know if it opens the input file successfully. Don't ignore exceptions, even if you don't know what to do with them, print them so you could analyze your problems later on.
Second, debug the code, see where it gets an exception, if at all, see what are the values at each step.
Third, to answer your question, assuming you work with Eclipse, if you refer to the file with relative path, the working directory is not the source / class folder, but the project folder.

Categories