FileInputStream not finding the file [closed]

2019-08-28 02:56发布

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?

标签: java java-io
2条回答
闹够了就滚
2楼-- · 2019-08-28 03:18

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.

查看更多
SAY GOODBYE
3楼-- · 2019-08-28 03:19

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:

System.out.println(new File(".").getAbsolutePath());

Options:

  • Specify an absolute filename
  • Specify a relative filename which takes into account where you're running this
  • Bundle the file as a resource and use Class.getResourceAsStream or similar

Note that this has nothing to do with BufferedReader - you're reading the text from System.in with no problems.

查看更多
登录 后发表回答