0

I am writing a Java program that can take user entries and save them into an ArrayList, then use the ArrayList to open a series of webpages. The program should also be able to read in web addresses from a file. This is where I'm having issues.

I'm currently gettting: The file bills.txt was not found. //the file is in my src folder

Exception in thread "main" java.lang.NullPointerException
    at PayBills.main(PayBills.java:92) //this is when the BufferdReader is closed

This isn't homework but the program shares concepts with a homework I am about to do, so I don't want to change anything fundamental about how I'm reading in the text. Any advice is appreciated!

import java.io.*;
import java.util.ArrayList;

    public class PayBills implements Serializable
    {
        /*The purpose of this program is to assist the user in opening a series of webpages to
         * pay bills online. The user will be able to save and edit a list of webpages,
         * open the newly created list, or read a list from file.
         */ 
        public static void main(String[] args) throws IOException
        {
            char input1;
            String line = new String();
            ArrayList<String> list1 = new ArrayList<String>();
            Runtime rt = Runtime.getRuntime();
            String filename = new String();

            try
            {
             // print out the menu
             rt.exec( "rundll32 url.dll,FileProtocolHandler " + "http://www.google.com");
             printMenu();

             // create a BufferedReader object to read input from a keyboard
             InputStreamReader isr = new InputStreamReader (System.in);
             BufferedReader stdin = new BufferedReader (isr);

             do
             {
                 System.out.println("\nWhat action would you like to perform?");
                 line = stdin.readLine().trim();  //read a line
                 input1 = line.charAt(0);
                 input1 = Character.toUpperCase(input1);
               if (line.length() == 1)   //check if a user entered only one character
               {
                   switch (input1)
                   {
                   case 'A':   //Add address process to array
                       System.out.println("\nPlease enter a web address to add to list:\n");
                       String str1 = stdin.readLine().trim();
                       if(str1.startsWith("http://www.") || str1.startsWith("https://www."))
                           list1.add(str1);
                       else
                       {
                           System.out.println("Please enter a valid web address (starting with http:// or https://).");
                       }
                       break;
                   case 'D':    //Show current list
                       System.out.println(list1.toString());
                       break;
                   case 'E':    //Execute current list
                       //rt.exec( "rundll32 url.dll,FileProtocolHandler " + "http://www.speedtest.net");
                       for(int i = 0; i < list1.size(); i++)
                       {
                           Process p1 = Runtime.getRuntime().exec("cmd /c start " + list1.get(i));                     
                       }
                       break;     
                   case 'R':   //Read list from file
                       System.out.println("\nPlease enter the filename to read: ");
                       {
                           filename = stdin.readLine().trim();
                       }
                       FileReader fr = null;
                       BufferedReader inFile = null;
                       try
                       {
                           fr = new FileReader(filename);
                           inFile = new BufferedReader(fr);
                           line = inFile.readLine();
                           System.out.println("Test2");
                           while(line != null)
                           {
                               System.out.println("Test3");
                               if(line.startsWith("http://www.") == false || line.startsWith("https://www.") == false)
                                   System.out.println("Error: File not in proper format.");
                               else 
                                   list1.add(line);
                           }
                               System.out.println(filename + " was read.");
                           }
                           catch(FileNotFoundException exception)
                           {
                               System.out.println("The file " + filename + " was not found.");
                               break;
                           }
                           catch(IOException exception)
                           {
                               System.out.println("Error. " + exception);
                           }
                           finally
                           {
                               inFile.close();
                           }  

                       break;
                   case '?':   //Display Menu
                       printMenu();
                       break;
                   case 'Q':    //Quit    
                       System.out.println("Goodbye!");
                       System.exit(0);
                   }//end switch
               }//end if
            else
                System.out.print("Unknown action\n");
             }//end do
             while (input1 != 'Q' || line.length() != 1);
            }

            catch(IOException e1) 
            {
                System.out.println("Error: " + e1);
            }
        }//end main
        public static void printMenu()
        {
            System.out.print("Choice\t\tAction\n" +
                             "------\t\t------\n" +
                             "A\t\tAdd Web Address to List\n" +
                             "D\t\tDisplay Current List\n" +
                             "E\t\tExecute Current List\n" +
                             "R\t\tRead List from File\n" +
                             "?\t\tDisplay Menu\n" +
                             "Q\t\tQuit\n");
        }//end of printMenu()

    }//end PayBills

Edit: Ok, the program is no longer crashing because I fixed the NPE, but I am still getting "The file bills.txt was not found.", which is the caught exception. As stated above, the file is located in my src folder so the path should be correct.

5
  • Is there another exception that gets printed with the System.out.println before you get the NPE? I think you get a FileNotFoundException at fr = new FileReader(filename); and then try to close a BufferedReader that hasn't been initialized. Commented Apr 5, 2013 at 18:07
  • if you are just providing the file name , place the file at location where you main program lies or give the file name as abosulte path like c:\myBills.txt Commented Apr 5, 2013 at 18:08
  • The file is located where the main program lies. Sotirios, the file not found error is a caught exception. I have a test print in the try block that does not print so the try block is not working. I understand why I get the NPE, but not why the try block isn't working. Commented Apr 5, 2013 at 18:11
  • what is the value you pass into the program as the file location? Commented Apr 5, 2013 at 18:12
  • see my answer for absolute path Commented Apr 5, 2013 at 18:14

6 Answers 6

3

If you are just passing the file name, then you have to append the location of the file before reading it

File file = new File(location + filename);

This is how it works if you only pass the filename as the argument to File constructor, it will try to look for the file at /Project/ directory (e.g. c:/workspace/project/test , if your project name is test and is located at c:/workspace/project)

So in order to pass the correct location you have to specify the complete path of the file that you are trying to read

so create the string location which will hold the location of the folder where the file is and then append the file name

String location = "C:/opt/files/";
String filename = "abc.txt";

File file = new File(location + filename);

This abc.txt should be located at "C:/opt/files/"

Remember I have added drive name because you are trying to run main

but if the same code is running on a server you have to specify the path relative to the root directory where the server is running

String location = "/opt/files/";

If you just pass the file name the code will look for the file in project folder not in the folder where your java class is.

Hope this helps.

Sign up to request clarification or add additional context in comments.

6 Comments

Could you expound on this? I'm not sure what you mean here. How would I implement this?
Edited my answer to explain
if you just pass the file name the code will look for the file in project folder not in the folder where your java class is.
Ok, this is very useful. I'll implement it once I get the program working. However, I am still having the problem even when the file is located in the same folder as the class.
That will not work because as I said, if you just pass the file name the code will look for the file in project folder not in the folder where your java class is. So if you want to read the file from your source folder you have use like this File file = new File("src/com/test/abc.txt"); and Please don't forget to accept and vote the answer
|
1

If just have to get out of the error for Null Poninter Exception from this to

 finally
                       {
                           inFile.close();
                       }  

to

finally{
         if (inFile!=null){
             inFile.close();
          }
       } 

3 Comments

Thank you, but this is not my primary concern. I really want to be able to read from a text file. Also, this isn't working for me. I get: "Syntax error on token "finally", invalid OnlySynchronized."
Can u copy paste this ideone.com/tJ1VOH code and paste the o/p that u get.,
Sorry I must have missed this.
1

if you are just providing the file name , place the file at location where you main program lies or give the file name as absoulte path like c:\myBills.txt

3 Comments

I have the file in the src folder of my program but it doesn't work.
could you tell where program exist and where file exists?
They both exist in the Eclipse src folder at C:\Users\John\Google Drive\School\CSE 205\PayBills\src
1

If I understand your issue correctly, the problem you're running into is that you're looking in the wrong directory. Java will look for the file relative to your working directory.

For example, if you are executing your program in ~/project and your file is located in ~/foo, you need to pass "..foo/bills.txt" in as your filepath or, equivalently, "~/foo".

If you are simply using bills.txt to test your program, you can always move it to the directory from which you execute your program.

Comments

1

NullPointerException is throwing because you are trying to close the infile which is still not being instantiated because the exception raised before it could be instantiated within your try-catch block. So You should change:

finally
{
     inFile.close();
} 

To

finally
{
        try
        {
          if(infile!=null)
          inFile.close();
        }catch(Exception ee){}

}

After your NPE is resolved. Here is the way that you could access your "Bill.txt" file. Use this code instead:

fr = new FileReader(new File(System.getProperty("home.dir"), filename));

1 Comment

@Johnny See my update to resolve your FileNotFoundException.
1

Here may not be THE solution, but could probably use some of it, the JFileChoser, a see how it's moves through the Stream, hope it helps at all.

import java.util.ArrayList;
import javax.swing.*;
import java.io.*;

public class TriArrayList {

  static ArrayList<String> arr = new ArrayList<String>();

  public static void imprimer(){
  System.out.println (arr);
  }

  public static void tri(){
  for (int i=0; i+1 < arr.size(); i++) {
     int a = arr.get(i).compareTo(arr.get(i+1));
        if (a > 0) {
            String b = arr.get(i);
            arr.set(i, arr.get(i+1));
            arr.set(i+1, b);
            if (i != 0)
                i -= 2;
        }  
  }
  }

  public static void main(String args[]){
  try {
      JFileChooser dial = new JFileChooser();
      int res = dial.showOpenDialog(null);
      if (res == JFileChooser.APPROVE_OPTION) {
          File f = dial.getSelectedFile();
          InputStream is = new FileInputStream(f);
          Reader r = new InputStreamReader(is);
          BufferedReader br = new BufferedReader(r);
          String line;
          while ((line = br.readLine()) != null) {
              line += "\n";
              arr.add(line);
          }
          is.close();
      }
  } catch (IOException e) {
  System.err.println("Problème de lecture du fichier blablabla.txt");
  }
  tri();
  imprimer();
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.