How to read a text file using a scanner in Java?

This is my code to read a text file. When I run this code, the output continues to say "File not found." This is a FileNotFoundException message. I am not sure what the problem is in this code.

Apparently this is part of java. For the entire java file, the user needs to enter something and create a text file using input as a name. After that, the user must enter the name of the previously created text file (suppose the user enters correctly), and then the program should read the text file. I correctly executed the other parts of my program, but the problem is that I entered the name again, it just cannot find the text file, although they are in the same folder.

 public static ArrayList<DogShop> readFile() { try { // The name of the file which we will read from String filename = "a.txt"; // Prepare to read from the file, using a Scanner object File file = new File(filename); Scanner in = new Scanner(file); ArrayList<DogShop> shops = new ArrayList<DogShop>(); // Read each line until end of file is reached while (in.hasNextLine()) { // Read an entire line, which contains all the details for 1 account String line = in.nextLine(); // Make a Scanner object to break up this line into parts Scanner lineBreaker = new Scanner(line); // 1st part is the account number try { int shopNumber = lineBreaker.nextInt(); // 2nd part is the full name of the owner of the account String owner = lineBreaker.next(); // 3rd part is the amount of money, but this includes the dollar sign String equityWithDollarSign = lineBreaker.next(); int total = lineBreaker.nextInt(); // Get rid of the dollar sign; // we use the subtring method from the String class (see the Java API), // which returns a new string with the first 'n' characters chopped off, // where 'n' is the parameter that you give it String equityWithoutDollarSign = equityWithDollarSign.substring(1); // Convert this balance into a double, we need this because the deposit method // in the Account class needs a double, not a String double equity = Double.parseDouble(equityWithoutDollarSign); // Create an Account belonging to the owner we found in the file DogShop s = new DogShop(owner); // Put money into the account according to the amount of money we found in the file s.getMoney(equity); s.getDogs(total); // Put the Account into the ArrayList shops.add(s); } catch (InputMismatchException e) { System.out.println("File not found1."); } catch (NoSuchElementException e) { System.out.println("File not found2"); } } } catch (FileNotFoundException e) { System.out.println("File not found"); } // Make an ArrayList to store all the accounts we will make // Return the ArrayList containing all the accounts we made return shops; } 
+8
java java.util.scanner
source share
6 answers

Well .. Apparently, the file does not exist or cannot be found. Try using the full path. You are probably reading from the wrong directory when you do not specify the path, unless the a.txt file is in your current working directory.

+4
source share

If you work in some IDEs, such as Eclipse or NetBeans, you should have this a.txt file in the root directory of your project. (and not in the folder where your .class files are created or elsewhere)

If not, you must provide an absolute path to this file.


Edit:
You will put the .txt file in the same place with .class (usually also a .java file, since you are compiling in the same folder) the compiled files if you compile it manually with javac . This is because it uses a relative path, and the path tells the JVM the path where the executable is located.

If you are using some IDE, it will generate compiled files for you using a Makefile or something similar for Windows and consider the default file structure, so it knows that the relative path starts from the project root folder.

+4
source share

I would recommend downloading the file as Resource and converting the input stream to a string. This will give you the flexibility to download the file anywhere with respect to the classpath.

0
source share

If you give a Scanner String object, it will read it as data. That is, "a.txt" does not open a file named "a.txt". It literally reads the characters "a", ".", "T", etc.

This corresponds to the main volume I of volume I, section 3.7.3.

If I find a solution to read the actual paths, I will come back and update this answer. The solution suggested by this text is to use

 Scanner in = new Scanner(Paths.get("myfile.txt")); 

But I can't get this to work because Path is not recognized by the compiler as a variable. Perhaps I am missing the import statement.

0
source share

This should help you ..:

 import java.io.*; import static java.lang.System.*; /** * Write a description of class InRead here. * * @author (your name) * @version (a version number or a date) */ public class InRead { public InRead(String Recipe) { find(Recipe); } public void find(String Name){ String newRecipe= Name+".txt"; try{ FileReader fr= new FileReader(newRecipe); BufferedReader br= new BufferedReader(fr); String str; while ((str=br.readLine()) != null){ out.println(str + "\n"); } br.close(); }catch (IOException e){ out.println("File Not Found!"); } } } 
0
source share

One more thing ... Instead of System.out.println("Error Message Here") use System.err.println("Error Message Here") . This will allow you to distinguish between the errors and the normal functioning of the code, displaying errors (i.e., Everything inside System.err.println() ) in red.

NOTE : it also works when using System.err.print("Error Message Here")

0
source share

All Articles