Reading a .txt file using Scanner class in Java - java

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();
}
}
}

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

here are some working and tested methods;
using Scanner
package io;
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
public static void main(String[] args) throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Here's another way to read entire file (without loop) using Scanner class
package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
using BufferedReader
package io;
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
BufferedReader br=new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine())!=null){
System.out.println(st);
}
}
}
using FileReader
package io;
import java.io.*;
public class ReadingFromFile {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
int i;
while((i=fr.read())!=-1){
System.out.print((char) i);
}
}
}

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:
URL url = insertionSort.class.getResource("10_Random");
File file = new File(url.toURI());
Specify the absolute file path via command-line arguments:
File file = new File(args[0]);
In Eclipse:
Choose "Run configurations"
Go to the "Arguments" tab
Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section

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.
for (int i =0 ; sc.HasNextLine();i++)
{
array[i] = sc.NextInt();
}
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.
for (int x=0;x< array.length ; x++)
{
System.out.println("array[x]");
}

You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.

private void loadData() {
Scanner scanner = null;
try {
scanner = new Scanner(new File(getFileName()));
while (scanner.hasNextLine()) {
Scanner lijnScanner = new Scanner(scanner.nextLine());
lijnScanner.useDelimiter(";");
String stadVan = lijnScanner.next();
String stadNaar = lijnScanner.next();
double km = Double.parseDouble(lijnScanner.next());
this.voegToe(new TweeSteden(stadVan, stadNaar), km);
}
} catch (FileNotFoundException e) {
throw new DbException(e.getMessage(), e);
} finally {
if(scanner != null){
scanner.close();
}
}
}

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.

You should use either
File file = new File("bin/10_Random.txt");
Or
File file = new File("src/10_Random.txt");
Relative to the project folder in Eclipse.

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.

At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.
you must use a file name by it's extension in File object constructor, as an example:
File myFile = new File("test.txt");
but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:
Scanner sc = new Scanner(Paths.get("test.txt"));
in this way you must import java.nio.file.Paths as well.

Related

Why do I get an "java.nio.file.NoSuchFileException" error even though the file exists?

I'm getting the error Exception in thread "main" java.nio.file.NoSuchFileException but I'm sure the file exists at the given location C:\\Users\\Admin\\Desktop\\Java.txt".
Why do I still get this error?
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Scanner;
public class ReadData {
public static void main(String[] args) throws IOException {
Scanner file = new Scanner(Paths.get("C:\\Users\\Admin\\Desktop\\Java.txt", "UTF-8"));
int int_value;
while ((file.hasNextInt())) {
int_value = file.nextInt();
System.out.println("Data:" + int_value);
}
file.close();
}
}
I believe your issue is with your Paths.get() method:
Scanner file = new Scanner(Paths.get("C:\\Users\\Admin\\Desktop\\Java.txt", "UTF-8"));
The closing parentheses for the Paths.get() method is in the wrong place. What you are actually supplying to the Scanner object (or what the get() method interprets it to be) is a path like this:
"C:\Users\Admin\Desktop\Java.txt\UTF-8"
That particular path obviously can not be found. It should be:
Scanner file = new Scanner(Paths.get("C:\\Users\\Admin\\Desktop\\Java.txt"), "UTF-8");
You may want to also consider utilizing the Try With Resources mechanism. It will auto-close the file reader:
try (Scanner file = new Scanner(Paths.get("C:\\Users\\Admin\\Desktop\\Java.txt"), "UTF-8")) {
int int_value;
while ((file.hasNextInt())) {
int_value = file.nextInt();
System.out.println("Data:" + int_value);
}
}
catch (IOException ex) {
ex.printStackTrace();
}
just keep the text file in your project folder and simply change the code like below
Scanner file=new Scanner(new File("Java.txt"));
hope it will solve your issue

Java Scanner doesn't read

I am trying to download a file that contains an integer from a remote machine, increase the value of the integer locally, write the new value to the same file and upload the file. I use scp. It downloads the file successfully. I use shell file for downloading and uploading processes. But I have problems with Scanner.
Here is the code:
import java.io.*;
import java.util.*;
public class shell {
public static void main(String[] args) throws IOException{
Runtime.getRuntime().exec("/home/ayyuce/Desktop/download.sh");
File f= new File("/home/ayyuce/Desktop/yeni.txt");
PrintWriter pw = new PrintWriter(f);
Scanner s= new Scanner(f);
int num=0;
if(s.hasNextLine()){
num=s.nextInt();
} else {
System.out.println("Error");
}
int increase=num++;
pw.println(increase);
Runtime.getRuntime().exec("/home/ayyuce/Desktop/upload.sh");
s.close();
pw.close();
}
}
The output is: Error
I wonder what is the problem with Scanner.
Thank you so much!
PrintWriter pw = new PrintWriter(f);
From javadoc
file - The file to use as the destination of this writer. If the
file exists then it will be truncated to zero size; otherwise, a new
file will be created. The output will be written to the file and is
buffered.
Of course, Scanner can't read anything, because the file was truncated to zero size in new PrintWriter(f).

Trying to Make a Vigenere Encrypter in Java [duplicate]

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();
}
}
}
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
here are some working and tested methods;
using Scanner
package io;
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner {
public static void main(String[] args) throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
Here's another way to read entire file (without loop) using Scanner class
package io;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadingEntireFileWithoutLoop {
public static void main(String[] args) throws FileNotFoundException {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
Scanner sc=new Scanner(file);
sc.useDelimiter("\\Z");
System.out.println(sc.next());
}
}
using BufferedReader
package io;
import java.io.*;
public class ReadFromFile2 {
public static void main(String[] args)throws Exception {
File file=new File("C:\\Users\\pankaj\\Desktop\\test.java");
BufferedReader br=new BufferedReader(new FileReader(file));
String st;
while((st=br.readLine())!=null){
System.out.println(st);
}
}
}
using FileReader
package io;
import java.io.*;
public class ReadingFromFile {
public static void main(String[] args) throws Exception {
FileReader fr=new FileReader("C:\\Users\\pankaj\\Desktop\\test.java");
int i;
while((i=fr.read())!=-1){
System.out.print((char) i);
}
}
}
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:
URL url = insertionSort.class.getResource("10_Random");
File file = new File(url.toURI());
Specify the absolute file path via command-line arguments:
File file = new File(args[0]);
In Eclipse:
Choose "Run configurations"
Go to the "Arguments" tab
Put your "c:/my/file/is/here/10_Random.txt.or.whatever" into the "Program arguments" section
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.
for (int i =0 ; sc.HasNextLine();i++)
{
array[i] = sc.NextInt();
}
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.
for (int x=0;x< array.length ; x++)
{
System.out.println("array[x]");
}
You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.
private void loadData() {
Scanner scanner = null;
try {
scanner = new Scanner(new File(getFileName()));
while (scanner.hasNextLine()) {
Scanner lijnScanner = new Scanner(scanner.nextLine());
lijnScanner.useDelimiter(";");
String stadVan = lijnScanner.next();
String stadNaar = lijnScanner.next();
double km = Double.parseDouble(lijnScanner.next());
this.voegToe(new TweeSteden(stadVan, stadNaar), km);
}
} catch (FileNotFoundException e) {
throw new DbException(e.getMessage(), e);
} finally {
if(scanner != null){
scanner.close();
}
}
}
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.
You should use either
File file = new File("bin/10_Random.txt");
Or
File file = new File("src/10_Random.txt");
Relative to the project folder in Eclipse.
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.
At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.
you must use a file name by it's extension in File object constructor, as an example:
File myFile = new File("test.txt");
but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:
Scanner sc = new Scanner(Paths.get("test.txt"));
in this way you must import java.nio.file.Paths as well.

having issues with Java reading input files using netbeans

Following is my code that I am working on for a school project. It does ok up until I try to read the animal.txt file. Can someone please tell me what I am doing wrong? I am attaching my compilation error as an image. Thanks in advance.
[input error image1
package finalproject;
//enabling java programs
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.io.FileInputStream;
import java.io.IOException;
public class Monitoring {
public static void choseAnimal() throws IOException{
FileInputStream file = null;
Scanner inputFile = null;
System.out.println("Here is your list of animals");
file = new FileInputStream("\\src\\finalproject\\animals.txt");
inputFile = new Scanner(file);
while(inputFile.hasNext())
{
String line = inputFile.nextLine();
System.out.println(line);
}
}
public static void choseHabit(){
System.out.println("Here is your list of habits");
}
public static void main(String[] args) throws IOException{
String mainOption = ""; //user import for choosing animal, habit or exit
String exitSwitch = "n"; // variable to allow exit of system
Scanner scnr = new Scanner(System.in); // setup to allow user imput
System.out.println("Welcome to the Zoo");
System.out.println("What would you like to monitor?");
System.out.println("An animal, habit or exit the system?");
mainOption = scnr.next();
System.out.println("you chose " + mainOption);
if (mainOption.equals("exit")){
exitSwitch = "y";
System.out.println(exitSwitch);
}
if (exitSwitch.equals( "n")){
System.out.println("Great, let's get started");
}
if (mainOption.equals("animal")){
choseAnimal();
}
if (mainOption.equals("habit")) {
choseHabit();
}
else {
System.out.println("Good bye");
}
}
}
\\src\\finalproject\\animals.txt suggests that the file is an embedded resource.
First, you should never reference src in you code, it won't exist once the program is built and package.
Secondly, you need to use Class#getResource or Class#getResourceAsStream in order to read.
Something more like...
//file = new FileInputStream("\\src\\finalproject\\animals.txt");
//inputFile = new Scanner(file);
try (Scanner inputFile = new Scanner(Monitoring.class.getResourceAsStream("/finalproject/animals.txt"), StandardCharsets.UTF_8.name()) {
//...
} catch (IOException exp) {
exp.printStackTrace();
}
for example
Now, this assumes that file animals.txt exists in the finalproject package
The error message clearly shows that it can't find the file. This means there's two possibilities:
File does not exist in the directory you want
Directory you want is not the directory you have.
I would start by creating a File object looking at "." (current directory) to and printing that to see what directory it looks by default. You may need to hard code the file path, depending on what netbeans is using for a default directory.

Java Cannot find file?

Hi I am trying to set up a scanner to print out contents of a text file. Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerReadFile {
public static void main(String[] args) {
// Location of file to read
File file = new File("CardNative.java.txt");
try
{
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
I have created a source folder in the project and put the text file in there. However I keep getting this error:
java.io.FileNotFoundException: CardNative.java.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at java.util.Scanner.<init>(Scanner.java:636)
at ScannerReadFile.main(ScannerReadFile.java:14)
You can use use System.out.println(System.getProperty("user.dir")); to see on what folder Java is looking by default for the file. If the file doesn't exist there you have to specify the entire path to the file.
This should work.
public static void main(String[] args) {
Scanner scanner = new Scanner(ScannerReadFile.class.getResourceAsStream("CardNative.java.txt"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
}
You need to make sure that your file is placed in the same directory from where you're running your program. Try adding this at the top of your main function, to see what's the current directory, and if your file is actually in that directory:
System.out.println(System.getProperty("user.dir"));
new File(String pathname);
The coinstructor you are using takes filepath as an argument, absolute or relative. If it is relative, it will be the execute path/your_string.
So you should put the file to the same folder as the compiled .jar file.
File file1 = new File("text.txt");
File file2 = new File("D:/documents/test.txt");
If the programm is executing from C:/programms/myprj.jar, so
file1 will open "C:/programms/test.txt" and file2 will open "D:/documents/test.txt" independently of the executing path.
http://docs.oracle.com/javase/7/docs/api/java/io/File.html#File(java.lang.String)
I was posting my answer in comment but I am not allowed to comment because I have no enough reputations. As in your comment, you are using back slashes in the file path. Instead use double back slashes \ OR one forward /. eg C:/java/file.txt
You should provide it the right and actual path of the file OR make sure that the file is lying there where your source is.
public class ScannerReadFile {
public static void main(String[] args) {
// Location of file to read
File file = new File("C:/Users/EastCorporation/Desktop/CardNative.java.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Categories