-2

In the program I am working on, I am trying to open a text file from the project folder so that I can later on read the integers from the file into an array. I am currently struggling with getting the compiler to locate the file. This is something I have done several times before, but this time around I currently am receiving an error saying that the system cannot find the file specified. The portion of the main class of my code, where the reading and writing of the file occurs, looks like this:

    if ("input".equals(input)) {
        System.out.println("Please enter the name of the input file: ");
        String filename = scanIn.nextLine();
         Scanner scanner = new Scanner(new File(filename));
        BufferedReader br = new BufferedReader(
    new InputStreamReader(new FileInputStream(filename)));
        int lineCount = 0;
        while (br.readLine() != null) {
            lineCount++;

        }

When prompted I enter sample.txt, the name of the text file in the project folder and it produces the error. Is there anything I am overlooking here that would cause this problem?

EDIT: The end goal of this is to load the integers from the file into an array, then perform Quick Sort on the array to sort it.

EDIT 2: Well in retrospect, this sounds like a very dumb error on my part, but I discovered what my problem was. Since this question has been marked as a duplicate, I can't post this as an answer so I'll post it as an edit. When creating my text file, the name of the file had become "sample.txt.txt" instead of "sample.txt" leading to the system not being able to find the file. There was no problem with the code or the filepath, just a dumb mistake on my part in naming the file.

user3068177
  • 357
  • 2
  • 5
  • 17

1 Answers1

-1

You can try the below code

 ClassLoader cLoader = this.getClassLoader();
 InputStream i = cLoader.getResourceAsStream("sample.txt");
Shravan Ramamurthy
  • 3,896
  • 5
  • 30
  • 44