I get this exception when I try to read from a file:
ERROR:
Exception in thread "main" java.io.FileNotFoundException: newfile.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at Postal.main(Postal.java:19)
import java.util.Scanner;
import java.io.*;
public class Postal {
public static void main(String[] args) throws Exception {
/*** Local Variables ***/
String line;
Scanner filescan;
File file = new File("newfile.txt");
filescan = new Scanner(file);
userInfo book = new userInfo();
/*** Loop through newfile.txt ***/
while (filescan.hasNext()) {
line = filescan.nextLine();
book.addNew(line);
}
book.print(0);
}
}
The class Scanner uses a FileInputStream to read the content of the file.
But it can't find the file so a exception is thrown.
You are using a relative path to the file, try out an absolute one.
Use this instead:
File file = new File(getClass().getResource("newfile.txt"));
Provide an absolute path the location where you want to create the file. And check that user has rights to create file there. One way to find the path is:
File f = new File("NewFile.txt");
if (!f.exists()) {
throw new FileNotFoundException("Failed to find file: " +
f.getAbsolutePath());
}
Try this to open file:
File f = new File("/path-to-file/NewFile.txt");
Related
I'm trying to read from a file using the Scanner and File class:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class TextFileReaderV1
{
public static void main(String[] args) throws IOException
{
String token = "";
File fileName = new File("data1.txt");
Scanner inFile = new Scanner(fileName);
while( inFile.hasNext() )
{
token = inFile.next( );
System.out.println(token);
}
inFile.close();
}
}
However, it is saying, "no such file or directory". and giving me the "java.io.FileNotFoundException"
I am using IntelliJ IDEA and the file is in the current directory I am working in: src/data1.txt -> next to GetFile.java (current code)
Full Error Message:
Exception in thread "main" java.io.FileNotFoundException: data1.txt (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at GetFile.main(GetFile.java:19)
**Edit: ** It has been solved!! The run configuration was set to the project directory, not the src one, so I implicitly added it in the argument:
File fileName = new File("src/data1.txt");
The run configuration was set to the project directory, not the src one, so I implicitly added it in the argument:
File fileName = new File("src/data1.txt");
Try entering the full path of the file. If that works, you can either be done at that point or look into relative file paths.
I'm currently trying to write a program that will read in a file line by line and add each line to an arrayList. My other function is supposed to sort the items from that buffer, then write them to a text file. However, I keep getting a FileNotFoundException, even when my file is sitting in the src directory, as well as the directory with my .class file. My code is as follows
public static ArrayList<String> readDictionary(String filename,
ArrayList<String> buffer) throws IOException, FileNotFoundException {
File f = new File(filename);
Scanner fileIn = new Scanner(f);
//Scanner fileIn = new Scanner(new File(filename));
boolean add = true;
while (fileIn.hasNextLine() == true) {
for (String s : buffer) {
if (fileIn.nextLine().equals(s)) {
add = false;
}
}
if (add == true) {
buffer.add(fileIn.nextLine());
}
add = true;
}
fileIn.close();
return buffer;
}
public static void writeDictionary(String filename, ArrayList<String> buffer) throws IOException, FileNotFoundException {
File f = new File(filename);
Collections.sort(buffer, String.CASE_INSENSITIVE_ORDER);
Path file = Paths.get(filename);
Files.write(file, buffer);
}
public static void main(String[] args) throws IOException, FileNotFoundException{
ArrayList<String> buffer = new ArrayList<>();
readDictionary("inputtest.txt", buffer);
}
Exception in thread "main" java.io.FileNotFoundException: inputtest.txt (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.util.Scanner.<init>(Scanner.java:611)
at UltimateDictionary.readDictionary(UltimateDictionary.java:18)
at UltimateDictionary.main(UltimateDictionary.java:46)
I tested this program by setting filename equal to "inputtest.txt", and that file is sitting in my src directory with the .java file, but it still throws the error. Also, how can I close the files? f.close() gives me an error.
The file in your src or .class directory, could only mean that the file is in classpath, while new File(filename); search the current working directory. To search classpath, change readDictionary method, after File f = new File(filename); add:
if (!f.exists()) {
URL url = <yourclassname>.class.getResource(filename);
if (url != null)
f = new File(url.getPath());
}
you have to use yourclassname.class because the method is static. Should work also:
if (url == null)
url = ClassLoader.getSystemResource(filename);
Iam trying to add a path (string) over an editfield in class main, the path will be taken to another class extract. After this I want to read the file with FileReader, but I got some error: file not found.
So I does some test:
I wrote the path directly in the FileReader -> everything Okay
I wrote a function File named sFile to get the path from class main and try to find the file behinde the path (exists). The file could be found but if FileReader trying to load the file got the same error
Code:
File sFile = new File(path);
if (sFile.exists()){
System.out.println("Found.");
System.out.println(sFile.getAbsolutePath());
try{
FileReader file = new FileReader(sFile); //db10916358-hp.sql (test file)
String[] fReadTmp = new String[10240000];//Just for testing
BufferedReader br = new BufferedReader(file);
String read = br.readLine();//Read a line
I found the error, it was an other File function which creates some files from the extract.
It was so simple, sorry for that.
Thanks for your time!
Try this snippet of code its work correctly
public static void readFile(String path) throws FileNotFoundException, IOException{
File file = new File(path);
if(file.exists())
{
FileReader fileReader = new FileReader(file); //db10916358-hp.sql (test file)
BufferedReader br = new BufferedReader(fileReader);
String read = br.readLine();//Read a line
}
else
{
System.out.print("Not Found");
}
}
I'm trying check and see if my program is scanning in the contents of a File however get this error:
Exception in thread "main" java.io.FileNotFoundException: input.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 lottery.main(lottery.java:40)
I don't see the problem as in my code as I always do my files this way, can't seem to understand to the problem.
Code:
public static void main(String[] args) throws FileNotFoundException
{
Scanner in = new Scanner(System.in);
System.out.println("Enter the name of the file with the ticket data.");
String input = in.nextLine();
File file = new File(input);
in.close();
Scanner scan = new Scanner(new FileInputStream(file));
int lim = scan.nextInt();
for(int i = 0; i < lim * 2; i++)
{
String name = scan.nextLine();
String num = scan.nextLine();
System.out.println("Name " + name);
}
scan.close();
}
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment. From docs.oracle.com
This means your FileInputStream wants an actual file system file provided. But you only made a filehandler when calling new File(). so you need to create the file on the file system calling file.createNewFile();
File file = new File(input); //here you make a filehandler - not a filesystem file.
if(!file.exists()) {
file.createNewFile(); // create your file on the file system
}
Scanner scan = new Scanner(new FileInputStream(file)); // read from file system.
Check if you start the jvm from the directory where the input file is located.
If not there is not possibility to find it with a relative path. Eventually change it to an absolute path (something like /usr/me/input.txt).
If the file is located on the directory where you start the java program check for the rights of the file. It could be not visible for the user launching the java program.
The problem is that your program could not find input.txt in the current working directory.
Look in the directory where is your program running and check it has a file called input.txt in it.
So there is the code:
public class Main{
public static void main(String[] argv) throws IOException{
new Main().run();
}
PrintWriter pw;
Scanner sc;
public void run() throws IOException{
sc = new Scanner(new File("input.txt"));
int a=sc.nextInt();
pw = new PrintWriter(new File("output.txt"));
pw.print(a*a);
pw.close();
}
}
Error:
Exception in thread "main" java.io.FileNotFoundException: input.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at Main.run(Main.java:14)
at Main.main(Main.java:8)
Like i understand it can't find file named input.txt, BUT! I have that file in same directory where Main class is, what can be the promblem then?
p.s Tried on cmd and eclipse, both give same error.
it is not relative to your Main class, it is relative from where you launch this Java program (i.e. current work directory)
it is relative to
System.getProperty("user.dir")
You probably need to specify the PATH to your file, one thing you can do is test for existence and readability with File.canRead() like
File file = new File("input.txt");
if (!file.canRead()) {
System.err.println(file.getCanonicalPath() + ": cannot be read");
return;
}
An example using a PATH might be (for Windows) -
File file = new File("c:/mydir/input.txt");
You can use System.out.println(System.getProperty("user.dir")) to see where Java is looking for the file by default. This is most likely your project folder. This is were you have to put the file if you don't want to specify an absolute path.