I'm trying to read a file but I can't seem to make it work. It shows an error: "File not found exception". The system cannot find the file specified. I enclosed the code below. Can anyone solve this issue?
package trailfiledemo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
*
* #author VIGNESH
*/
public class Trailfiledemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
FileReader fr=new FileReader("C:\\Users\\VIGNESH\\Documents\\ga and pso\\hellodata.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Check if your file exists within the designated file path as it needs to match. Another possibility that Joik mentioned above, is your compiler might not have permission to access the file within the path given. You could try an alternative file path if that is the case.
FileNotFound exception has wrong name. It may appear not only in case the file is absent, so there is an ambiguity.
There are three cases where a FileNotFoundException may be thrown:
1.The file does not exist.
2.The file is actually a directory.
3.The file cannot be opened. It may have no read access in your OS.
You need to check all 3 fail cases to be sure about the root of the issue. Documentation page contains some details:
https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html
I implemented your code and only changed your username to mine and it compiled like a charm. Read everything in the file and ended succesfully.
Try:
Click on Run > Clean and Build Project maybe it didn't take one of your changes.
Other things you might want to try:
use a buffered reader:
try (BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\VIGNESH\\Documents\\ga and pso\\hellodata.txt"))) {
String line;
while ((line = br.readLine()) != null)
System.out.print(line + "\n");
}
Or you could move the file into the same folder as the code and use this path '"src\stackoverflow\hellodata.txt"' stackoverflow => your package´s name
Related
I am trying to write a program (for school homework) that will take a command-line argument to specify a directory, and for the time being, just print out the files in the directory. I have literally been looking at various answers and trying things out for hours now, and just have no idea what to do. Below, you will find my current code. when I open a CMD, and type java DirectoryFiles c:\ .
I get Error, could not find or load main class DirectoryFiles. I just used c:\ to see if I could get any directory to print out.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class DirectoryFiles
{
/**
* Gets command line argument for directory to be used in program.
*
* #param args
*/
public static void main(String[] args)
throws IOException, ClassNotFoundException
{
String path = args[0];
File dir = new File(path);
FileInputStream fis = new FileInputStream(dir);
if ((dir).isDirectory())
{
File[] files = dir.listFiles();
System.out.println(files);
}
}
}
Most likely you have only the source file (you didn't compile it).
Remember that:
Java is not an interpreter of a source file.
java command attempts to run an existing java class.
So you must start from compiling the source code into a Java class.
Then you can run it with java command.
I have a class that reads a file:
package classlibrary;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
public class ReadingResource {
public static String readResource() throws IOException {
URL resource = ClassLoader.getSystemClassLoader().getResource("classlibrary/test_file.txt");
BufferedReader br = new BufferedReader(new FileReader(resource.getPath()));
return br.readLine();
}
}
The resource file is in the same directory where this class is.
I made a library out of this class and the file.
Now I want to use it in the other class:
package uritesting;
import classlibrary.ReadingResource;
import java.io.IOException;
public class URITesting {
public static void main(String[] args) throws IOException {
System.out.println(ReadingResource.readResource());
}
}
When I make a .jar file out of this class, set the class as the main class, add the .jar from above and execute it as "java -jar URITesting.jar" I get a FileNotFoundException, saying the class ReadingResource can not find the specified file. It is funny because the path that is specified in the exception message is actually the correct path to the file.
You can find the files here.
EDIT:
I developed the project in NetBeans. When I run it there, it works fine. The classpath is different in that case. It contains both resources of the URITestingProject and ReadingResource.
However, when I run it as a standalone JAR, the classpath contains URITestingProject only. What is strange to me is that it doesn't complain about not finding the class ReadingResource. It means that it is loaded, although it is not in the classpath :/
The problem is resource.getPath(). It's not possible to calculate a path ,valid for a file reader, inside a jar file, on another server and so on. However you can get the data through a stream instead:
InputStream data = ClassLoader.getSystemClassLoader().getResourceAsStream("classlibrary/test_file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(data, "utf-8"));
As a side note: When reading with reader it's a good idea to specify the encoding:
Why the program search the file:
File FILE_PATH = new File("C:\\Users\\home\\Desktop\\DbWord.txt");
System.out.println(FILE_PATH.exists());
System.out.println(FILE_PATH.getAbsoluteFile());
FileInputStream fIn = new FileInputStream(FILE_PATH);
Scanner reader = new Scanner(fIn);
at: C:\Users\home\Documents\NetBeansProjects\MyDatabase\C:\Users\home\Desktop\DbWord.txt
How can i counteract the default location?
If something in this post not good, please tell me and no negative vote.
Thanks!
why negative votes??????????????? whats your problems??????????
Please double check your error details. You might have seen something like the below error. Actually the program is not searching for the file "C:\Users\home\Documents\NetBeansProjects\MyDatabase\C:\Users\home\Desktop\DbWord.txt", it is trying to locate the file "C:\Users\home\Desktop\DbWord.txt" which does not exists in your machine. You are seeing "C:\Users\home\Documents\NetBeansProjects\MyDatabase\C:\Users\home\Desktop\DbWord.txt" along with the error because you have already used System.out.println(FILE_PATH.getAbsoluteFile()); statement in your code.
false
Exception in thread "main" java.io.FileNotFoundException: C:\Users\home\Desktop\DbWord.txt (The filename, directory name, or volume label syntax is incorrect)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
C:\Users\home\Documents\NetBeansProjects\MyDatabase\C:\Users\home\Desktop\DbWord.txt
at com.stackoverflow.answer.SimpleFileHelper.main(SimpleFileHelper.java:17)
Hope you are clear now.
There are three main chances where a FileNotFoundException may be thrown.
The named file does not exist.
The named file is actually a directory not file.
The named file cannot be opened for reading due to some reason.
The first two reasons are unlikely based on your description, please check the third point using file.canRead() method.
If the test above returns true, I would suspect the following:
You might have forgotten to explicitly throw or catch the potential exception (i.e., FileNotFoundExcetion). If you work in an IDE, you should have got some complaint from the compiler. But I suspect you didn't run your code in such an IDE.
Try the following code and see if the exception would be gone:
package com.stackoverflow.answer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class SimpleFileHelper {
public static void main(String[] args) throws FileNotFoundException {
File FILE_PATH = new File("C:/Users/home/Desktop/DbWord.txt");
System.out.println(FILE_PATH.exists());
System.out.println(FILE_PATH.getAbsoluteFile());
FileInputStream fIn = new FileInputStream(FILE_PATH);
Scanner reader = new Scanner(fIn);
}
}
by running this...
File file = new File("Highscores.scr");
i keep getting this error, and i really don't know how to get around it.
the file is currently sitting in my source packages with my .java files.
I can quite easily read the file by specifying the path but i intend to run this on multiple computers so i need the file to be portable with the program.
this question isnt about reading the text file but rather specifying its location without using an absolute path .
ive searched for the answer but the answers i get are just "specify the name" and "specify the absolute path".
id post an image to make it more clear but i dont have the 10 rep to do so :/
how do i do this?
cheers.
The best way to do this is to put it in your classpath then getResource()
package com.sandbox;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
public class Sandbox {
public static void main(String[] args) throws URISyntaxException, IOException {
new Sandbox().run();
}
private void run() throws URISyntaxException, IOException {
URL resource = Sandbox.class.getResource("/my.txt");
File file = new File(resource.toURI());
String s = FileUtils.readFileToString(file);
System.out.println(s);
}
}
I'm doing this because I'm assuming you need a File. But if you have an api which takes an InputStream instead, it's probably better to use getResourceAsStream instead.
Notice the path, /my.txt. That means, "get a file named my.txt that is in the root directory of the classpath". I'm sure you can read more about getResource and getResourceAsStream to learn more about how to do this. But the key thing here is that the classpath for the file will be the same for any computer you give the executable to (as long as you don't move the file around in your classpath).
BTW, if you get a null pointer exception on the line that does new File, that means that you haven't specified the correct classpath for the file.
As far as I remember the default directory with be the same as your project folder level. Put the file one level higher.
-Project/
----src/
----test/
-Highscores.scr
If you are building your code on your eclipse then you need to put your Highscores.scr to your project folder. Try that and check.
You can try to run the following sample program to check which is the current directory your program is picking up.
File f = new File(".");
System.out.println("Current Directory is: " + f.getAbsolutePath());
I posted a similar question here: Read from a file containing integers - java but couldn't get a decent reply.
Now I have written this new code which only reads a file and outputs the result.
I get a FileNotFoundException whenever I try to read from a file. The code is below:
import java.io.*;
public class second {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
File f = new File("C:\\Users\\Haroon\\workspace\\ppp\\temperature.txt");
FileReader file = new FileReader(f);
BufferedReader buf = new BufferedReader(file);
String s = null;
while((s = buf.readLine()) != null){
System.out.println(s);
}
}
}
This is strange because the file is in the project's folder.
Any help would be appreciated.
That should work. Go to the location of the file, copy the path, paste it in your code, and escape the slashes. You are missing something.
Also check that the name/extension of the file is correct, you could have something like "temperature.txt.txt".
I don't know why you are unable to read the file. Its working fine on my system. Since you are making you project in eclipse. I will post a workaround here.
System.out.println(System.getProperty("user.dir"));
Use this command to find the current user directory at the time of execution. Now directly place the file in that user directory. Now you can directly read the file just by its name.
For eg:
File f = new File("temperature.txt");
Also as mentioned by 'lxxx' do check the file name and the extension by enabling show file extension option in Windows.