I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.
I am getting the following error messages:
java.io.FileNotFoundException: 10_Random (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 insertionSort.main(insertionSort.java:14)
I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class insertionSort {
public static void main(String[] args) {
File file = new File("10_Random");
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file. Please log the file.getAbsolutePath() to verify that file is correct.
Make sure the filename is correct (proper capitalisation, matching extension etc - as already suggested).
Use the
Class.getResource
method to locate your file in the classpath - don't rely on the current directory:Specify the absolute file path via command-line arguments:
In Eclipse:
private void loadData() {
The file you read in must have exactly the file name you specify:
"10_random"
not "10_random.txt" not "10_random.blah", it must exactly match what you are asking for. You can change either one to match so that they line up, but just be sure they do. It may help to show the file extensions in whatever OS you're using.Also, for file location, it must be located in the working directory (same level) as the final executable (the .class file) that is the result of compilation.
10_Random.txt
.int
before reading anint
. It is not safe to check withhasNextLine()
and then expect anint
withnextInt()
. You should usehasNextInt()
to check that there actually is anint
to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.No one seems to have addressed the fact that your not entering anything into an array at all. You are setting each int that is read to "i" and then outputting it.
Something to this effect will keep setting values of the array to the next integer read.
Than another for loop can display the numbers in the array.