I am getting the following exception.
java.util.NoSuchElementException: No line found
I got this error while writing a larger program which needed to read from a text file, and so decided to do a test.
Scanner scan = new Scanner(new File("restrictions.txt");
String s1 = scan.nextLine();
System.out.println(s1);
And I still get the exception. I have a text file in the same folder as the class called restrictions.txt which has text in it. What am I doing wrong?
new File("restrictions.txt") will look for the file in the "Start dir" of your app - if you're using Eclipse, it's probably the root of your project.
To open the file next to your class, you can use the Scanner constructor which accepts an InputStream that you get by
YourClass.class.getResourceAsStream("restrictions.txt")
You should use if(in.hasNextLine()) before calling in.nextLine(). Otherwise for last line it will thrown Line not found exception.
Javadoc for Scanner
Do you need to specify a line ending so it knows what a line is?
Related
I have an assignment for my CS class where it says to read a file with several test scores and asks me to sum and average them. While summing and averaging is easy, I am having problems with the file reading. The instructor said to use this syntax
Scanner scores = new Scanner(new File("scores.dat"));
However, this throws a FileNotFoundException, but I have checked over and over again to see if the file exists in the current folder, and after that, I figured that it had to do something with the permissions. I changed the permissions for read and write for everyone, but it still did not work and it still keeps throwing the error. Does anyone have any idea why this may be occurring?
EDIT: It was actually pointing to a directory up, however, I have fixed that problem. Now file.exists() returns true, but when I try to put it in the Scanner, it throws the FileNotFoundException
Here is all my code
import java.util.Scanner;
import java.io.*;
public class readInt{
public static void main(String args[]){
File file = new File("lines.txt");
System.out.println(file.exists());
Scanner scan = new Scanner(file);
}
}
There are a number situation where a FileNotFoundException may be thrown at runtime.
The named file does not exist. This could be for a number of reasons including:
The pathname is simply wrong
The pathname looks correct but is actually wrong because it contains non-printing characters (or homoglyphs) that you did not notice
The pathname is relative, and it doesn't resolve correctly relative to the actual current directory of the running application. This typically happens because the application's current directory is not what you are expecting or assuming.
The path to the file is is broken; e.g. a directory name of the path is incorrect, a symbolic link on the path is broken, or there is a permission problem with one of the path components.
The named file is actually a directory.
The named file cannot be opened for reading for some reason.
The good news that, the problem will inevitably be one of the above. It is just a matter of working out which. Here are some things that you can try:
Calling file.exists() will tell you if any file system object exists with the given name / pathname.
Calling file.isDirectory() will test if it is a directory.
Calling file.canRead() will test if it is a readable file.
This line will tell you what the current directory is:
System.out.println(new File(".").getAbsolutePath());
This line will print out the pathname in a way that makes it easier to spot things like unexpected leading or trailing whitespace:
System.out.println("The path is '" + path + "'");
Look for unexpected spaces, line breaks, etc in the output.
It turns out that your example code has a compilation error.
I ran your code without taking care of the complaint from Netbeans, only to get the following exception message:
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - unreported exception java.io.FileNotFoundException; must
be caught or declared to be thrown
If you change your code to the following, it will fix that problem.
public static void main(String[] args) throws FileNotFoundException {
File file = new File("scores.dat");
System.out.println(file.exists());
Scanner scan = new Scanner(file);
}
Explanation: the Scanner(File) constructor is declared as throwing the FileNotFoundException exception. (It happens the scanner it cannot open the file.) Now FileNotFoundException is a checked exception. That means that a method in which the exception may be thrown must either catch the exception or declare it in the throws clause. The above fix takes the latter approach.
The code itself is working correctly. The problem is, that the program working path is pointing to other place than you think.
Use this line and see where the path is:
System.out.println(new File(".").getAbsoluteFile());
Obviously there are a number of possible causes and the previous answers document them well, but here's how I solved this for in one particular case:
A student of mine had this problem and I nearly tore my hair out trying to figure it out. It turned out that the file didn't exist, even though it looked like it did. The problem was that Windows 7 was configured to "Hide file extensions for known file types." This means that if file appears to have the name "data.txt" its actual filename is "data.txt.txt".
Hope this helps others save themselves some hair.
I recently found interesting case that produces FileNotFoundExeption when file is obviously exists on the disk.
In my program I read file path from another text file and create File object:
//String path was read from file
System.out.println(path); //file with exactly same visible path exists on disk
File file = new File(path);
System.out.println(file.exists()); //false
System.out.println(file.canRead()); //false
FileInputStream fis = new FileInputStream(file); // FileNotFoundExeption
The cause of the problem was that the path contained invisible \r\n characters at the end.
The fix in my case was:
File file = new File(path.trim());
To generalize a bit, the invisible / non-printing characters could have include space or tab characters, and possibly others, and they could have appeared at the beginning of the path, at the end, or embedded in the path. Trim will work in some cases but not all. There are a couple of things that you can help to spot this kind of problem:
Output the pathname with quote characters around it; e.g.
System.out.println("Check me! '" + path + "'");
and carefully check the output for spaces and line breaks where they shouldn't be.
Use a Java debugger to carefully examine the pathname string, character by character, looking for characters that shouldn't be there. (Also check for homoglyph characters!)
An easy fix, which worked for me, is moving my files out of src and into the main folder of the project. It's not the best solution, but depending on the magnitude of the project and your time, it might be just perfect.
Reading and writing from and to a file can be blocked by your OS depending on the file's permission attributes.
If you are trying to read from the file, then I recommend using File's setReadable method to set it to true, or, this code for instance:
String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file;
File f = new File(arbitrary_path);
f.setReadable(true);
data_of_file = Files.readAllBytes(f);
f.setReadable(false); // do this if you want to prevent un-knowledgeable
//programmers from accessing your file.
If you are trying to write to the file, then I recommend using File's setWritable method to set it to true, or, this code for instance:
String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file = { (byte) 0x00, (byte) 0xFF, (byte) 0xEE };
File f = new File(arbitrary_path);
f.setWritable(true);
Files.write(f, byte_array);
f.setWritable(false); // do this if you want to prevent un-knowledgeable
//programmers from changing your file (for security.)
Apart from all the other answers mentioned here, you can do one thing which worked for me.
If you are reading the path through Scanner or through command line args, instead of copy pasting the path directly from Windows Explorer just manually type in the path.
It worked for me, hope it helps someone :)
I had this same error and solved it simply by adding the src directory that is found in Java project structure.
String path = System.getProperty("user.dir") + "\\src\\package_name\\file_name";
File file = new File(path);
Scanner scanner = new Scanner(file);
Notice that System.getProperty("user.dir") and new File(".").getAbsolutePath() return your project root directory path, so you have to add the path to your subdirectories and packages
You'd obviously figure it out after a while but just posting this so that it might help someone. This could also happen when your file path contains any whitespace appended or prepended to it.
Use single forward slash and always type the path manually. For example:
FileInputStream fi= new FileInputStream("D:/excelfiles/myxcel.xlsx");
What worked for me was catching the exception. Without it the compiler complains even if the file exists.
InputStream file = new FileInputStream("filename");
changed to
try{
InputStream file = new FileInputStream("filename");
System.out.println(file.available());
}
catch (Exception e){
System.out.println(e);
}
This works for me. It also can read files such txt, csv and .in
public class NewReader {
public void read() throws FileNotFoundException, URISyntaxException {
File file = new File(Objects.requireNonNull(NewReader.class.getResource("/test.txt")).toURI());
Scanner sc = new Scanner(file);
while (sc.hasNext()) {
String text = sc.next();
System.out.println(text);
}
}
}
the file is located in resource folder generated by maven. If you have other folders nested in, just add it to the file name like "examples/test.txt".
I have an assignment for my CS class where it says to read a file with several test scores and asks me to sum and average them. While summing and averaging is easy, I am having problems with the file reading. The instructor said to use this syntax
Scanner scores = new Scanner(new File("scores.dat"));
However, this throws a FileNotFoundException, but I have checked over and over again to see if the file exists in the current folder, and after that, I figured that it had to do something with the permissions. I changed the permissions for read and write for everyone, but it still did not work and it still keeps throwing the error. Does anyone have any idea why this may be occurring?
EDIT: It was actually pointing to a directory up, however, I have fixed that problem. Now file.exists() returns true, but when I try to put it in the Scanner, it throws the FileNotFoundException
Here is all my code
import java.util.Scanner;
import java.io.*;
public class readInt{
public static void main(String args[]){
File file = new File("lines.txt");
System.out.println(file.exists());
Scanner scan = new Scanner(file);
}
}
There are a number situation where a FileNotFoundException may be thrown at runtime.
The named file does not exist. This could be for a number of reasons including:
The pathname is simply wrong
The pathname looks correct but is actually wrong because it contains non-printing characters (or homoglyphs) that you did not notice
The pathname is relative, and it doesn't resolve correctly relative to the actual current directory of the running application. This typically happens because the application's current directory is not what you are expecting or assuming.
The path to the file is is broken; e.g. a directory name of the path is incorrect, a symbolic link on the path is broken, or there is a permission problem with one of the path components.
The named file is actually a directory.
The named file cannot be opened for reading for some reason.
The good news that, the problem will inevitably be one of the above. It is just a matter of working out which. Here are some things that you can try:
Calling file.exists() will tell you if any file system object exists with the given name / pathname.
Calling file.isDirectory() will test if it is a directory.
Calling file.canRead() will test if it is a readable file.
This line will tell you what the current directory is:
System.out.println(new File(".").getAbsolutePath());
This line will print out the pathname in a way that makes it easier to spot things like unexpected leading or trailing whitespace:
System.out.println("The path is '" + path + "'");
Look for unexpected spaces, line breaks, etc in the output.
It turns out that your example code has a compilation error.
I ran your code without taking care of the complaint from Netbeans, only to get the following exception message:
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - unreported exception java.io.FileNotFoundException; must
be caught or declared to be thrown
If you change your code to the following, it will fix that problem.
public static void main(String[] args) throws FileNotFoundException {
File file = new File("scores.dat");
System.out.println(file.exists());
Scanner scan = new Scanner(file);
}
Explanation: the Scanner(File) constructor is declared as throwing the FileNotFoundException exception. (It happens the scanner it cannot open the file.) Now FileNotFoundException is a checked exception. That means that a method in which the exception may be thrown must either catch the exception or declare it in the throws clause. The above fix takes the latter approach.
The code itself is working correctly. The problem is, that the program working path is pointing to other place than you think.
Use this line and see where the path is:
System.out.println(new File(".").getAbsoluteFile());
Obviously there are a number of possible causes and the previous answers document them well, but here's how I solved this for in one particular case:
A student of mine had this problem and I nearly tore my hair out trying to figure it out. It turned out that the file didn't exist, even though it looked like it did. The problem was that Windows 7 was configured to "Hide file extensions for known file types." This means that if file appears to have the name "data.txt" its actual filename is "data.txt.txt".
Hope this helps others save themselves some hair.
I recently found interesting case that produces FileNotFoundExeption when file is obviously exists on the disk.
In my program I read file path from another text file and create File object:
//String path was read from file
System.out.println(path); //file with exactly same visible path exists on disk
File file = new File(path);
System.out.println(file.exists()); //false
System.out.println(file.canRead()); //false
FileInputStream fis = new FileInputStream(file); // FileNotFoundExeption
The cause of the problem was that the path contained invisible \r\n characters at the end.
The fix in my case was:
File file = new File(path.trim());
To generalize a bit, the invisible / non-printing characters could have include space or tab characters, and possibly others, and they could have appeared at the beginning of the path, at the end, or embedded in the path. Trim will work in some cases but not all. There are a couple of things that you can help to spot this kind of problem:
Output the pathname with quote characters around it; e.g.
System.out.println("Check me! '" + path + "'");
and carefully check the output for spaces and line breaks where they shouldn't be.
Use a Java debugger to carefully examine the pathname string, character by character, looking for characters that shouldn't be there. (Also check for homoglyph characters!)
An easy fix, which worked for me, is moving my files out of src and into the main folder of the project. It's not the best solution, but depending on the magnitude of the project and your time, it might be just perfect.
Reading and writing from and to a file can be blocked by your OS depending on the file's permission attributes.
If you are trying to read from the file, then I recommend using File's setReadable method to set it to true, or, this code for instance:
String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file;
File f = new File(arbitrary_path);
f.setReadable(true);
data_of_file = Files.readAllBytes(f);
f.setReadable(false); // do this if you want to prevent un-knowledgeable
//programmers from accessing your file.
If you are trying to write to the file, then I recommend using File's setWritable method to set it to true, or, this code for instance:
String arbitrary_path = "C:/Users/Username/Blah.txt";
byte[] data_of_file = { (byte) 0x00, (byte) 0xFF, (byte) 0xEE };
File f = new File(arbitrary_path);
f.setWritable(true);
Files.write(f, byte_array);
f.setWritable(false); // do this if you want to prevent un-knowledgeable
//programmers from changing your file (for security.)
Apart from all the other answers mentioned here, you can do one thing which worked for me.
If you are reading the path through Scanner or through command line args, instead of copy pasting the path directly from Windows Explorer just manually type in the path.
It worked for me, hope it helps someone :)
I had this same error and solved it simply by adding the src directory that is found in Java project structure.
String path = System.getProperty("user.dir") + "\\src\\package_name\\file_name";
File file = new File(path);
Scanner scanner = new Scanner(file);
Notice that System.getProperty("user.dir") and new File(".").getAbsolutePath() return your project root directory path, so you have to add the path to your subdirectories and packages
You'd obviously figure it out after a while but just posting this so that it might help someone. This could also happen when your file path contains any whitespace appended or prepended to it.
Use single forward slash and always type the path manually. For example:
FileInputStream fi= new FileInputStream("D:/excelfiles/myxcel.xlsx");
What worked for me was catching the exception. Without it the compiler complains even if the file exists.
InputStream file = new FileInputStream("filename");
changed to
try{
InputStream file = new FileInputStream("filename");
System.out.println(file.available());
}
catch (Exception e){
System.out.println(e);
}
This works for me. It also can read files such txt, csv and .in
public class NewReader {
public void read() throws FileNotFoundException, URISyntaxException {
File file = new File(Objects.requireNonNull(NewReader.class.getResource("/test.txt")).toURI());
Scanner sc = new Scanner(file);
while (sc.hasNext()) {
String text = sc.next();
System.out.println(text);
}
}
}
the file is located in resource folder generated by maven. If you have other folders nested in, just add it to the file name like "examples/test.txt".
Hi i am using LibGDX to program android.
Is there some way to sraightforward access specific line on the file without going through all the lines and reading them until i reach desired line? (Can I just say I want to read line number so-and-so?)
I know there are such methods:
FileHandle file = Gdx.files.internal("list.txt");
BufferedReader reader = new BufferedReader(file.reader());
reader.readLine(); <--- but it reads only first line !
//// or using scanner
scanner1 = new Scanner(new File("list.txt"));
scanner1.nextLine(); <--- also reads first line ..
Can I do it without looping through unnecessary lines? Any solutions, workarounds welcome. Thanx
I want to write a few arguments in a .txt file and I want to sort them. To do that I want to go to the next line for every groop of arguments but I dont know how to do that.I have tried the:
x.nextLine();
statement, but that is only for scanning and not for formatting.
How can I go to the next line of a file while formatting? Is there another statement for that?
This is the code I created:
try{
w = new Formatter("data.txt");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Fatal Error, please Reboot or reinstal program", "Error", JOptionPane.PLAIN_MESSAGE);
}
w.format("%s,%s,%s,%s%n", book,code,author,editor);
w.close();
You write
w.format("%s,%s,%s,%s%n", book,code,author,editor);
and I assume you want a newline where you write %n. But newline is \n, so change your code to
w.format("%s,%s,%s,%s\n", book,code,author,editor);
Also, you may want to revise the error catching logic in the program: right now if opening the file fails, you show an error message, which is good, but after that your program continues execution and will crash and burn on the first write operation...
EDIT: every time you execute the line w.format("%s,%s,%s,%s\n", book,code,author,editor); a line terminated by a new line will be added to the file, as long as you don't close the file or restart the program, because the Javadoc for the constructor you use says:
fileName - The name of the file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
So, if you need a file that grows instead of being overwritten you should use one of the other available constructors, eg one accepting an Appendable as argument. This would lead to the following code:
FileWriter fstream = new FileWriter("data.txt",true);
Formatter w = new Formatter(fstream);
// do whatever your program needs to do
w.close();
Of course surrounded by the necessary exception handling.
I'm doing a very simple text-parsing program, using files given to me by a friend.
However, when I open the file using a Scanner like so,
Scanner scan = new Scanner(new File(path));
System.err.println(scan.hasNext());
while(scan.hasNextLine())
System.err.println(scan.nextLine());
System.err.println(scan.next());
result:
false
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1364)
at Test.main(Test.java:18)
the scanner treats the file(which is some 1400 lines long) as empty.
Can anyone think of any reason a scanner might not be able to see a file? I suspect the fact that the file was imported from a Windows machine to a Linux machine may have something to do with it, but my mind is open to other possibilities
edited for formatting and code errors
I resolved it using new Scanner(new BufferedReader(new FileReader(fileName))) instead of new Scanner(new File(fileName))
Found the problem:
Looked at the file byte by byte. found an EOF character in the first byte.
Java was ignoring the rest of the file.
EDIT: Fisrt guess was wrong
The file might have 1400 lines full of whitespaces.
it maybe occurred for this problems:
1-your file maybe isn't created.
2-your file is in use for other programs.
3-the path address is false.