Filenotfoundexception JAVA, need full path [duplicate] - java

This question already has answers here:
java.io.FileNotFoundException: the system cannot find the file specified
(8 answers)
Closed 4 years ago.
My program get a filename in parameter but if i want to use it i need the full directory path or i get filenotfoundexception.
For example:
My program got sample.txt in parameter from C:\Users\me\documents.
File file = new File(args[0]);
FileReader fr = new FileReader(file);
That throw filenotfoundexception.
So what should i use to locate the file?
I saw so many similar question but i didnt find solution :(
I tried to use getResources and getPath but nothing.

You can open a file with just the filename if that file exists in the same directory as of your source code. If the file is located at any random location then you need to give the complete path of the file along with its name.
Eg: c:\documents\sample.txt
Or another thing that you can try is recursively going through all folders present in your file system and locate the file. However, this is will be a very horrible solution.

File fileName = new File("myfile.txt");
if(!fileName.exists()) {
fileName.createNewFile();
}
FileOutputStream oFile = new FileOutputStream(fileName, false);
add this code if your file is not on the location this will create a one for you then you wont be getting filenotfound exception at the latter part

Related

How to open a file in the same directory as the .jar file of the application? [duplicate]

This question already has answers here:
How to get the real path of Java application at runtime?
(15 answers)
Closed 6 years ago.
I'm trying to load a .txt file into an arrayList in java using a combination of relative paths.
My jar file is in /usr/tool/dist/tool.jar
The file I want to load is in /usr/tool/files/file.txt
I think I was able to retrieve the path of my tool.jar, but how can I go from that path to the one where my file is?
I have the following code
// String path should give me '/usr/tool'
File f = new File(System.getProperty("java.class.path"));
File dir = f.getAbsoluteFile().getParentFile();
String path = dir.toString();
String table1 = this should represent /usr/tool/files/file.txt
BufferedReader buf_table1 = new BufferedReader(new FileReader(new File(table1)));
To find the path of your jar file being executed, java.class.path is not the right property. This property may contain more than one file, and you cannot know which is the right one. (See the docs.)
To find the path of the correct jar file, you can use this instead:
URL url = MainClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
Where MainClass the main class of your tool, or any other class in the same jar file.
Next, the parent File of a file is its directory. So the parent File of /usr/tool/dist/tool.jar is /usr/tool/dist/. So if you want to get to /usr/tool/files/file.txt, you need to get the parent of the parent, and then from there files/file.txt.
Putting it together:
File jarFile = new File(MainClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
File file = new File(jarFile.getParentFile().getParent(), "files/file.txt");

Where i Can find text file created by servlet in Eclipse

This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.

Obtain path to file with filename [duplicate]

This question already has answers here:
Get path of Android resource
(3 answers)
How can I write a Drawable resource to a File?
(2 answers)
Closed 8 years ago.
I am writing an Android app and I need to do something I would consider incredibly simple, yet am having the hardest time figuring out.
How can I obtain the path to a JPG file so that I can upload it to a server?
The file is snoopy.jpg and is in the res/drawable folder
I've tried:
File sourceFile = new File("android.resource://com.appname.something/drawable/snoopy");
But, that's not a file
I've tried:
File sourceFile = new File("drawable/snoopy");
and that doesn't work.
I tried putting snoopy.jpg in the root of the app directory and attempting:
File sourceFile = new File("/snoopy.jpg");
And that still didn't work.
Any help would be greatly appreciated!
Try this :
InputStream is = getResources().openRawResource(R.drawable.snoopy);
You can open an InputStream from your drawable resource using the above code. Also, before doing any file operation, you need to check if file.exist() and if it returns false then you need to create a file via f.createNewFile();

FileNotFoundException though canRead() and exists() returns true [duplicate]

This question already has answers here:
Java FileNotFoundException even though file exists
(2 answers)
Closed 9 years ago.
I do this and write some content to this file.
fileSymbol = new File("D:\\TempFiles\\SymbolFile.xml");
fileSymbol.createNewFile();
prSymbol = new PrintWriter(fileSymbol);
while(//condition goes here){
prSymbol.write(text);
}
Then I try to read from this file as,
FileReader fr = new FileReader(fileSymbol);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
When I try to run, it gives the following exception
java.io.FileNotFoundException: fileSymbol (The system cannot find the file specified)
When I try
fileSymbol.canRead();
fileSymbol.exists();
returns true for both.
I do not understand why I get this error though I have already created the file. When I check the location manually, I am able to see my created file.
PS: I have just provided the code snippet of my code.
Add the following before you read the file
prSymbol.close();
It is not required to call flush() before close .Reference JavaDoc - close()
java.io.FileNotFoundException: fileSymbol (The system cannot find the file specified)
That message, if you have transcribed it accurately, can only mean that you are using "fileSymbol" as the file name, where previously you were using "D:\\TempFiles\\SymbolFile.xml".
NB calling createNewFile() the line before you create an output stream or writer to the same file is a complete waste of time.

Problem with Java FileReader [duplicate]

This question already has answers here:
FileNotFoundException, the file exists Java [closed]
(2 answers)
Closed 7 years ago.
Hello I have this in my code
File file = new File("words.txt");
Scanner scanFile = new Scanner(new FileReader(file));
ArrayList<String> words = new ArrayList<String>();
String theWord;
while (scanFile.hasNext()){
theWord = scanFile.next();
words.add(theWord);
}
But for some reason I am getting a
java.io.FileNotFoundException
I have the words.txt file in the same folder as all of my .java files
What am I doing wrong? Thanks!
Tip: add this line to your code...
System.out.println(file.getAbsolutePath());
Then compare that path with where your file actually is. The problem should be immediately obvious.
The file should reside in the directory from which you execute the application, i.e. the working directory.
Generally it's a good idea to package data files with your code, but then using java.io.File to read them is a problem, as it's hard to find them. The solution is to use the getResource() methods in java.lang.ClassLoader to open a stream to a file. That way the ClassLoader looks for your files in the location where your code is stored, wherever that may be.
try:
URL url = this.getClass().getResource( "words.txt" );
File file = new File(url.getPath());
You haven't specified an absolute path. The path would therefore be treated as a path, relative to the current working directory of the process. Usually this is the directory from where you've launched the Main-Class.
If you're unsure about the location of the working directory, you can print it out using the following snippet:
System.out.println(System.getProperty("user.dir"));
Fixing the problem will require adding the necessary directories in the original path, to locate the file.

Categories