Java FileNotFoundException although file is there - java

I set up the method to try/catch this error. My issue is that it catches the fileNotFoundException for Trivia.txt even when I explicitly created Trivia.txt in the same package. I can't figure out why the file is not being found. I did some looking around for the answer to my problem, and had no luck. Anyway, here's my code
public static void readFile(){
try{
File file = new File("Trivia.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
}
catch(FileNotFoundException e){
System.out.println("file not found");
System.out.println();
}
catch(IOException e){
System.out.println("error reading file");
}
}
The code here is just a method of the TextHandler class that is called statically by WindowComp class (totally unrelated class). The package is mainPackage which holds the main() and WindowComp() and textHandler() alond with Triva.Txt

The way you open the file, it's supposed to be found in the current working directory, not in the subdirectory your source is found.
Try System.out.println(file.getCanonicalPath()) in order to find out where the code is expecting the file.

Try loading your file as a Resource, like this
URL fileURL = this.getClass().getResource("Trivia.txt");
File file = new File(fileURL.getPath());
This will load your file from the same package of the class who loads the resource.
You can also provide an absolute path for your file, using
URL fileURL = this.getClass().getResource("/my/package/to/Trivia.txt");

If the file is found somewhere away from the current package of the class, you can also provide an absolute path directly to the constructor:
File file = new File("path/to/file/Trivia.txt");
You can also use a different constructor such as the one indicated in this answer:
Java - creating new file, how do I specify the directory with a method?
For further information, there's always the documentation:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html

Related

Java - File IO - AbsolutePath() does not return the path to the file

I have been trying to get this method working for the past few days always coming back to the same problem. My file won't open unless the file path is specified and formatted.
This is my code:
text = new MyArrayList<>();
String filePath = new File(fileName).getAbsolutePath();
filePath = filePath.replace('\\', '/');
try {
Scanner s = new Scanner(new File(filePath));
while (s.hasNext()) {
text.add(s.next());
}
s.close();
}
catch(FileNotFoundException e){
System.out.println("File not found.");
}
For some reason when I invoke the getAbsolutePath(), it gives me this path : "C:/Zaid/College/CE2336/Programs/File.txt"
whereas the file path that actually allows me to access the file is:
"C:/Zaid/College/CE2336/Programs/MyImplementations/File.txt"
I don't understand what I should do to clean this up.
P.S. The MyImplementations is the package where the text file and my code reside in.
When you call
String filePath = new File(fileName).getAbsolutePath();
you are creating file in your root directory of the project and then getting that path instead of the file you already have and want to get
This should be sufficient in your case:
Scanner s = new Scanner(new File(fileName));
Also ensure when handling errors you share all the information you have: Print the file that was not found. You will see that this makes troubleshooting just so much easier.
catch(FileNotFoundException e){
System.out.println("File not found.");
e.printStackTrace(System.out);
}

Reading text file works in IDE but not in .jar

I am using
File file = new File("res/movies.txt");
to read text from a bundled .txt file. My code works perfectly when running the program within IntelliJ IDEA, but when I create a .jar file and run it, it gives a "File not found" error. What can I do to make the code work both in the IDE as well as in the jar file?
You need to load the file as a resource. You can use Class.getResourceAsStream or ClassLoader.getResourceAsStream; each will give return an InputStream for the resource.
Once you've got an InputStream, wrap it in an InputStreamReader (specifying the appropriate encoding) to read text from it.
If you need to sometimes read from an arbitrary file and sometimes read from a resource, it's probably best to use separate paths to either create a FileInputStream for the file or one of the methods above for a resource, then do everything else the same way after that.
Here's an example which prints each line from resources/names.txt which should be bundled in the same jar file as the code:
package example;
import java.io.*;
import java.nio.charset.*;
public class Test {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
Test.class.getResourceAsStream("/resources/names.txt"),
StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}
try to change
File file = new File("res/movies.txt");
to
File file = new File("res/movies.jar");
this of course assumes the filename is movies.jar

JAVA - File I/O cant get file to read

I'm trying to get inventory.csv to load in Eclipse, and I'm not sure where I'm supposed to put the location of the file (Example: c:\\Users\\...) or if I even need it, considering it's in the same folder. I recieved an "unable to load inventory.csv." output. My driver finishes the rest of the program with no errors afterwards.
public int readInventory(Automobile[] inventory)
{
final String FILENAME = "inventory.csv";
int size = 0;
Scanner input = new Scanner("inventory.csv");
try
{
input = new Scanner(new File(FILENAME));
}
catch (FileNotFoundException e)
{
System.out.println("Unable to open file " + FILENAME + ".");
}
// ...
return size;
}
Here is the output I'm getting with no syntax errors.
Unable to open file inventory.csv.
considering it's in the same folder.
Same folder as what? inventory.csv was not present in the current working directory when you executed your program.
If you are trying to read a CSV file from a single Java program then directly keep your file in the same location where the class was created.
In eclipse, keep the CSV file directly under your project directory. As you can see, the Employee.xml file directly under JavaPrac project.enter image description here
You should try this
try{
FileReader fr=new FileReader(filename);
BufferedReader br =new BufferedReader(fr)
String lime=br.readLine();
br.close();
catch(Exeption e){}

Always getting FileNotFoundException in java

I am using Scanner to read the File contents. For that I am using the following code.
public static void main (String[] args) throws IOException {
File file = new File("/File.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()) {
// Until the end
System.out.print(sc.nextLine());
}
sc.close();
}
But this code always throws FileNotFoundException. I have tried Googling this, but I can't find where to check the file. Secondly, I have created files with same name in almost every directory to check when would the Code catch the presence of file.
You can see in the Package I have created a file named File.txt so that code can find it whereever it looks for.
In the Java docs, I get to know that the File accepts a String parameter as
File file = new File("file_name");
But what sort or what would be the param here, isn't told. Can I get the help?
I think you want File file = new File("File.txt"); instead of File file = new File("/File.txt");, get rid of the slash. If what you want is a relative path, you want .\File.txt
As #deterministicFail says in the comments, it is not a good idea to hardcode path separators, instead use System.getProperty("path.separator"); This way your code should work in multiple plataforms, so your code would be:
To make it plataform independent (Asuming you are using a relative path):
File file = new File("." + System.getProperty("path.separator") + "File.txt");
Replace the line
File file = new File("/File.txt");
with
File file = new File(".\\File.txt");
or
File file = new File("File.txt");
File f=new File("testFile.txt");
For this kind of referral you need to put file in root of your eclipse project (In parallel of src). This problem is only when you are Using Eclipse IDE.
Best solution for this kind of problems is checking AbsolutePath of the file
System.out.println(f.getAbsolutePath());
It will give you path where your code is looking for file.
There are two possibilities if you are looking for the file in the working directory then either use "File.txt" or "./File.txt". In case of windows one more option would be to use ".\File.txt).
If that is not what you are looking for, you can check which path the file refers to using either of the two sysouts immediately after instantiating the file, which will give you the absolute path on your machine.
File f = new File("/File.txt");
System.out.println(f.getAbsolutePath());
System.out.println(f.getAbsoluteFile().getAbsolutePath());
I have never done it the way you did but this is how I read files.
This is the purpose of the class FileInpuStream. I use a buffer to get bytes.
If it is only a problem of path, why don't you simply use the complete path ? You can copy paste it from the file information.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
FileInputStream fis = null;
try {
// object I use to read files
fis = new FileInputStream(new File("File.txt"));
byte[] buf = new byte[8];
int n = 0;
// while there is something in the file
while ((n = fis.read(buf)) >= 0) {
for (byte bit : buf) {
// do what you want
System.out.print("\t" + bit + "(" + (char) bit + ")");
System.out.println("");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Try not to use the / in File.txt, and if you really have to, use the backslash instead \ since you're in Windows

Not able to open HDFS file from mapper Hadoop

I searched a lot but failed to find a solution to this problem.
Actually the file I want to access is in HDFS, but not in input path (the path which was input to the map/reduce job). And I want to access it from mapper.
The hdfs path specified in the input path is perfectly accessible from mapper but the other hdfs files are not.
INside mapper:-
FileSystem FS1=FileSystem.get(conf);
Path path=new Path(""+FS1.getHomeDirectory());
FSDataInputStream fsdis=FS1.open(path);
RESULTS IN the following ERROR:
java.io.IOException : Cannot open filename /user/hadoop
Thanks in advance,
Harsh
I remember using this tutorial to get something similar working. You can give it a try, it has only a few difference tho what you've written but still it might help...
#Edit: ah and I just noticed (after reading the comments) that you are trying to open FS1.getHomeDirectory() and that is a directory. You should point out to a file not a directory, I think (you can check it out in the linked tutorial under "Reading data from a file").
can u try this once
try {
FileSystem fs = FileSystem.get (new Configuration ());
FileStatus[] status = fs.listStatus (new Path ("hdfs://jp.seka.com:9000/user/jeka/in"));
for (int i=0;i < status.length;i++) {
BufferedReader br = new BufferedReader (new InputStreamReader (fs.open (status[i].getPath())));
String line;
line = br.readLine();
while (line != null) {
System.out.println (line);
line=br.readLine ();
}
}
} catch (Exception e) {
System.out.println("File not found");
}

Categories

Resources