Java 无法读取文件

标签 java bufferedreader filereader

我正在编写一个Java程序,它可以获取用户条目并将它们保存到ArrayList中,然后使用ArrayList打开一系列网页。该程序还应该能够从文件中读取网址。这就是我遇到问题的地方。

我目前得到:找不到文件 bills.txt。//该文件位于我的 src 文件夹中

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

这不是作业,但该程序与我即将要做的作业共享概念,因此我不想改变我在文本中阅读方式的任何基本内容。如有任何建议,我们将不胜感激!

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

编辑:好的,程序不再崩溃,因为我修复了 NPE,但我仍然收到“找不到文件 bills.txt。”,这是捕获的异常。如上所述,该文件位于我的 src 文件夹中,因此路径应该是正确的。

最佳答案

如果您只是传递文件名,则必须在读取文件之前附加文件的位置

File file = new File(location + filename);

这就是它的工作原理 如果您仅将文件名作为参数传递给 File 构造函数,它将尝试在/Project/目录中查找文件(例如 c:/workspace/project/test ,如果您的项目名称是 test 并且位于 c:/工作区/项目)

因此,为了传递正确的位置,您必须指定您尝试读取的文件的完整路径

因此创建字符串位置,该位置将保存文件所在文件夹的位置,然后附加文件名

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

File file = new File(location + filename);

此 abc.txt 应位于“C:/opt/files/”

记住我已经添加了驱动器名称,因为您正在尝试运行 main

但是如果相同的代码在服务器上运行,则必须指定相对于服务器运行的根目录的路径

String location = "/opt/files/";

如果您只传递文件名,代码将在项目文件夹中查找文件,而不是在 java 类所在的文件夹中查找文件。

希望这有帮助。

关于Java 无法读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15840554/

相关文章:

java - 无法更改子类中的公共(public)变量类型

java - 这个代码段的时间复杂度是O(n^2)还是O(n^3)

java只是花括号

Java从文本(txt)文件中读取字符串

java - BufferedReader——通过 token 而不是 readLine() 读取?

java - 在 Java main 和方法之间传递信息

java - 拆分字符串时 ArrayIndexOutOfBounds

java - 使用线程计算不同单词的数量

java - java.io.PrintWriter 和 java.io.BufferedWriter 的区别?

java - 我的java程序中的资源泄漏