I am making a program in java that will read a file and put each word from it into an array so I can make an anagram of each word after sorting them to a default array. I have a good idea of how to do this, except my .txt file is not being read. I have a file called "input.txt" in the src with the "anagram.java" program I am writing, but when the code promts for the file entry, upon entering the file name "input.txt" my code says the file does not exist and I get this:
Enter file name:
input.txt
Exception in thread "main" java.io.FileNotFoundException: input.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.io.FileInputStream.<init>(FileInputStream.java:79)
at java.io.FileReader.<init>(FileReader.java:41)
at anagram.main(anagram.java:23)
Java Result: 1
BUILD SUCCESSFUL (total time: 6 seconds)
Here is the code at the line where is messing up:
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter file name: ");
String fileName = br.readLine();
File file = new File(fileName);
if(file.length() == 0)
{
System.out.println("File is empty");
System.exit(1);
}
Apparently typing in "input.txt" is not enough information or something, I'm not sure. I removed the
if(file.length() == 0)
{
System.out.println("File is empty");
System.exit(1);
}
To get the error I stated above, which is how I figured out it wasn't even recognizing the file in the src with the anagram.java prgm.
What is wrong with my code? Why is it not reading the file or saying it isn't there?
It's looking in a path different than your source directory. Try specifying a full path like
c:\input.txt
(but don't forget to move your file there!) to see what I mean.I dare say the file is in the
src
directory - but I suspect that's not the current working directory of the program. To check this, run this code:Options:
Class.getResourceAsStream
or similarNote that this has nothing to do with
BufferedReader
- you're reading the text fromSystem.in
with no problems.