0

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.

AsdFork
  • 15
  • 5
  • You can get the current directory and add it to the path if necessary. However, you must also deal with whether the specified args[0] is a relative or absolute path before blindly adding the current directory. If you are using Java 8, look at the `Path` object as well to potentially help. – KevinO Apr 15 '16 at 16:27
  • just try printing out `args[0]` and see what it is. Your file should exists if that path is correct.. – 3kings Apr 15 '16 at 16:28
  • When i am printing out args[0].getAbsolutePath its give a totaly different path where doesnt exist sample.txt The simple getPath gives back sample.txt – AsdFork Apr 15 '16 at 16:32

2 Answers2

0
 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

Priyamal
  • 2,919
  • 2
  • 25
  • 52
  • But i want to use the datas from the file. – AsdFork Apr 15 '16 at 16:41
  • src/file.txt - this is a format of a file path add this one to your code with the code i've provided maybe you dont have the permission to read the file you are trying to read – Priyamal Apr 15 '16 at 16:45
  • still the same, seems like its only searching it in the project folder and not in the others. Probably i must add the full path to find the file. – AsdFork Apr 15 '16 at 16:57
0

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.

Touchstone
  • 5,575
  • 7
  • 41
  • 48
  • This answer is incorrect, so I have downvoted it. The current working directory is not usually the same as the directory that contains the source code. – Robin Green Dec 03 '18 at 21:26
  • Did I say anywhere that current working directory is always the directory that contains the source code? Gal – Touchstone Dec 04 '18 at 16:38
  • You only talked about the directory that contains the source code. But the current working directory is what matters. They may or may not be the same. – Robin Green Dec 04 '18 at 16:39