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(); } } }
Reading a file with ScannerScanner class can be used to read file in Java. Earlier we have seen examples of reading file in Java using FileInputStream and reading file line by line using BufferedInputStream and in this Java tutorial, we will See How can we use Scanner to read files in Java.
Scanner is a utility class in java. util package which can parse primitive types and strings using regular expressions. It can read text from any object which implements the Readable interface. We can also construct a Scanner that produces values scanned from the specified file.
There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.
You have to put file extension here
File file = new File("10_Random.txt");
Use following codes to read the file
import java.io.File; import java.util.Scanner; public class ReadFile { public static void main(String[] args) { try { System.out.print("Enter the file name with extension : "); Scanner input = new Scanner(System.in); File file = new File(input.nextLine()); input = new Scanner(file); while (input.hasNextLine()) { String line = input.nextLine(); System.out.println(line); } input.close(); } catch (Exception ex) { ex.printStackTrace(); } } }
-> This application is printing the file content line by line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With