Eclipse Reads From File But Runnable .jar File Doesnt - java

I'm making a simple game.
Eclipse reads a text file but when I export my project as runnable jar file it doesn't read it.
My resource folder looks like this: http://i.stack.imgur.com/LK2SF.png
The code:
BufferedReader br = new BufferedReader(
new FileReader("Resources/LevelManager/LevelManager.txt"));
When i run runnable jar file I get this error:
java.io.FileNotFoundException: Resources\LevelManager\LevelManager.txt (System cant find the path)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at LevelManager.Utils.getLevel(Utils.java:13)
at LevelManager.LevelManager.<init>(LevelManager.java:15)
at State.GameState.<init>(GameState.java:26)
at Main.Game.init(Game.java:54)
at Main.Game.run(Game.java:80)
at java.lang.Thread.run(Unknown Source)`
Thank you for your answers.

This is a classical error.
Your application will run in its own jar; which means its resources will be included in the jar and not available as File objects. You need to use a classloader.
I'm not sure how you intend to read from the resource but here is how to obtain a stream from a resource (and please note that slashes are used for separators, always:
#WillNotClose //this is a JSR 305 annotation
public static InputStream loadResource(final String resourcePath)
throws IOException
{
final URL url = EnclosingClass.class.getResource(resourcePath);
if (url == null)
throw new IOException(resourcePath + ": resource not found");
return url.openStream();
}

Related

How to solve the java.nio.file.NoSuchFileException?

I have a file called "result.csv", from that file i want to read certain data and display them. I have that file in my eclipse project folder itself. Still i'm unable to read the file.
public static void main(String [] args) {
int i=0;
String filename="result.csv";
Path pathToFile = Paths.get(filename);
try (BufferedReader br = Files.newBufferedReader(pathToFile, StandardCharsets.US_ASCII)) {
// read the first line from the text file
String line = br.readLine();
// loop until all lines are read
while (i<10) {
// use string.split to load a string array with the values from
// each line of
// the file, using a comma as the delimiter
String[] attributes = line.split(",");
double x=Double.parseDouble(attributes[8]);
double y=Double.parseDouble(attributes[9]);
System.out.println(GeoHash.withCharacterPrecision(x, y, 10));
// read next line before looping
// if end of file reached, line would be null
line = br.readLine();
i++;
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
OUTPUT:
java.nio.file.NoSuchFileException: result.csv
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.spi.FileSystemProvider.newInputStream(Unknown Source)
at java.nio.file.Files.newInputStream(Unknown Source)
at java.nio.file.Files.newBufferedReader(Unknown Source)
at com.uvce.cse.searchiot.geohash.TestGeoHash.main(TestGeoHash.java:19)
Can anyone point where exactly i missed? and how can i overcome this or any alternate methods for this method?
The problem is that your default directory at application startup is not what you think it is. Try adding the following line to your code, just after you create the path:
public static void main(String [] args) {
int i=0;
String filename="result.csv";
Path pathToFile = Paths.get(filename);
System.out.println(pathToFile.toAbsolutePath());
That way, you'll see exactly where it is looking for the file.
How to fix it is your decision. You can use a full path spec instead of just a filename, or put the filename in a special "Resources" directory and reference it using a relative path, or move the file to wherever your default directory is.
If your file("result.csv") in the src directory, you should use the "src/result.csv" instead of "result.csv".
The problem there is that java isn't able to find the "result.csv" file in the project folder. Thus, try to use the fully qualified path to the file, e.g. C:\your_folder\project\result.csv in the Path variable. Also I think It would be better to use bufferedreader like this: BufferedReader br = new BufferedReader(new FileReader(insert here the String in which is defined the path to the file)); Check the uses of BufferedReader here
If you're a MacOSX user please type the file path manually instead of copying it from "Get Info".
You'll get something like this if you copied it from "Get Info":
/Users/username<200e><2068><2068>/Desktop<2069>/source.txt
I had the same error caused by escaped characters on windows file path. For example, my application was looking for "C:\Users\david\my%20folder%20name\source.txt" meanwhile the real path was "C:\Users\david\my folder name\source.txt".
Not discarding all possible solutions here, this error also occurs when your running Android Studio on Windows environment and using a project directory on an external hard drive formatted with other than NFTS. ]
If this is the case, simply move your project into the main HDD (NTFS) and reload the project again , this time from the main HDD folder path.

PrintWriter : java.io.FileNotFoundException: The system cannot find the path specified

Without pasting the entire code here, the line where the exception keeps happening is :
PrintWriter prtwrt = new PrintWriter(new File(directoryName+File.separator+stud.getIndex()+".txt"));
I have consulted the internet, and the books I have on Java, and by all logic it ought to work, but it doesn't. Can someone explain as to why it doesn't work, or perhaps propose a solution?
Stacktrace :
java.io.FileNotFoundException: students\0096-03.txt (The system cannot find the path specified)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileWriter.<init>(Unknown Source)
at StudentsManager.main(StudentsManager.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:267)
Also, directoryName, as the name implies, is the name of the directory where the file should be created. In this case it is "students".
So lets have
File f=new File(directoryName+File.separator+stud.getIndex()+".txt");
First lets check if path exists and create dir tree if it does not:
if(!f.getParentFile().exists()) f.getParentFile().mkdirs();
now you can try to create Writer
PrintWriter prtwrt = new PrintWriter(f);
PrintWriter should create new file if not yet exists; If for some reasons it will not work, create file beforeheand with f.createNewFile()
All together it must work.
try to enter the full path to the file because you might enter a relative path.
If you want to check if you have found the file try the following code:
File file = new File(...);
if(!file.exists()) {
System.out.println("File not found!");
return;
}

Java.io.FileNotFoundException for a file that's there

I am currently creating a err... annoying program that repeatedly plays a ding sound, but there is a error whenever I run it. I have tried everything, and the file IS in the correct spot. Here is my current code:
public class PlaySound {
public static void main(String[] args) throws Exception {
while (true) {
String path = PlaySound.class.getProtectionDomain().getCodeSource().getLocation().getPath().replaceAll("%20", " ");;
InputStream in = new FileInputStream(path + "//src//ding.wav");
AudioStream audioStream = new AudioStream(in);
AudioPlayer.player.start(audioStream);
TimeUnit.SECONDS.sleep(1);
}
}
}
And yes, I have used other formats of the code like //src//ding.wav
Any help would be appreciated.
EDIT: also the error is
Exception in thread "main" java.io.FileNotFoundException: C:\Users\*** ******\Desktop\ding.jar\src\ding.wav (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at net.lookatthis.PlaySound.main(PlaySound.java:19)
EDIT2: The error is older before I renamed the file. I changed the error to reflect the current filename
I think you're trying to read a resource in a jar file specifying the absolute path of your hard disk drive.
ding.jar\src\hit.wav
So there are two alternatives, or unzip your ding.jar file into a directory.
Or specify the relative path and access to the file using the classloader resource reader.
Using the resource reader you can find to the hit.wav file using
InputStream in = PlaySound.class.getResource("/ding.wav").openStream();
AudioStream audioStream = new AudioStream(in);
You probably need to unjar your ding.jar to expand its file structure. FileInputStream (probably?) can't access the jar'ed version of this file.

Java Exception error i/o

I am getting an error when I try to read my file abc.txt in my D drive.
Even I tried format : "D:\EDU\java\abc.txt"
Here's my code :
package javapro;
import java.io.FileInputStream;
public class office {
public static void main (String[] args)throws Exception {
FileInputStream apple = new FileInputStream ("D:/EDU/java/abc.txt");
int din;
while ((din=apple.read())!=-1){
System.out.println((char)din);
}
apple.close();
}
}
My Error :
Exception in thread "main" java.io.FileNotFoundException: D:\EDU\java\abc.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at javapro.office.main(office.java:8)
Make sure the file is actually located in that directory. Right-click and click on Properties to check the path.
If you've done that, change all the \ to / or \\.
The error is self-explanatory. The file isn't where you have told the application it is. Check your path to make sure that it leads to the file.
1) Change the code as below
FileInputStream apple = new FileInputStream ("D:\\EDU\\java\\abc.txt");
or
InputStream is = getClass().getResourceAsStream("abc.txt");
//if abc.txt is present in classpath
From InputStream, you have to read the data.
EDIT: Resolve non static error
InputStream is = office.class.getClass().getResourceAsStream("abc.txt");

FileNotFoundException in server project in eclipse

I work on a indexing project which create a file dynamically for all words start with same character and the name of that file is created based on first character of the words like:
file "a" contains apple, adapt,air,...
file "b" contains book, bad,bar,...
My project work correctly when I run through application but when I run it through server(tomcat) I got the following error for the given line of the code:
BufferedReader reader = new BufferedReader(new FileReader(getFileName(word)));
INFO: Server startup in 2785 ms
java.io.FileNotFoundException: C (The system cannot find the file specified)
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 DataLayer.FileRepository.getArrayListPosting(FileRepository.java:54)
I add the path to this word in the following code but I got the same error.
BufferedReader reader = new BufferedReader(new FileReader(getFileName("C:\\code\\"+word)));
what should I do, where should I put this file in eclipse?
This is the image of my files in my project.
Put file "word" in the main Eclipse project directory. Don't worry about adding the path as per your 2nd try.
java.io.FileNotFoundException: C (The system cannot find the file specified)
You probably forgot the : in the path, and accidently made it C\\File which is looking for a directory named C, which doesnt exist.
The problem is that calling function which create the name of the project as argument of fileReader.The solution is :
String str= path+getFileName(word);
BufferedReader reader = new BufferedReader(new FileReader(str));
Any of these two solutions
1________
put the "word" file in the eclipse project directory. i.e the folder that contains the eclipse.exe application file
2_______
File file=new File("theFileFullPath");
According to your program, do it this way => File file= new File("C:\code\"+word)));
then::
BufferedReader reader = new BufferedReader(new FileReader(file.getAbsolutePath()));

Categories