Java无法从文件中读取

Java无法从文件中读取,java,bufferedreader,filereader,Java,Bufferedreader,Filereader,我正在编写一个Java程序,可以获取用户条目并将其保存到ArrayList中,然后使用ArrayList打开一系列网页。该程序还应该能够从文件中读取web地址。这就是我遇到问题的地方 我目前正在获取:找不到文件bills.txt//该文件位于我的src文件夹中 Exception in thread "main" java.lang.NullPointerException at PayBills.main(PayBills.java:92) //this is when the Buf

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

我目前正在获取:找不到文件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文件夹中,因此路径应该是正确的。

如果必须从这个到

 finally
                       {
                           inFile.close();
                       }  


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

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

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

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

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类所在的文件夹中


希望这能有所帮助。

如果您只是提供文件名,请将文件放在主程序所在的位置,或者将文件名作为绝对路径,如c:\myBills.txt

如果我正确理解您的问题,您遇到的问题是您在错误的目录中查找。Java将查找与工作目录相关的文件

例如,如果您在~/project中执行程序,并且您的文件位于~/foo中,则需要将..foo/bills.txt作为文件路径传入~/foo

如果您只是使用bills.txt来测试您的程序,则始终可以将其移动到执行程序的目录。

引发NullPointerException是因为您试图关闭尚未实例化的填充,因为在try-catch块中实例化该异常之前引发该异常。所以你应该改变:

finally
{
     inFile.close();
} 

解决NPE后。以下是访问Bill.txt文件的方法。请改用此代码:

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

这里可能不是解决方案,但可能会使用其中的一些JFileChoser,看看它是如何在流中移动的,希望它能有所帮助

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

在获得NPE之前,是否还有另一个使用System.out.println打印的异常?我认为在fr=newfilereaderfilename时会出现FileNotFoundException;然后尝试关闭尚未初始化的BufferedReader。如果只是提供文件名,请将文件放在主程序所在的位置,或将文件名作为结果路径,如c:\myBills.txt。该文件位于主程序所在的位置。Sotirios,文件未找到错误是捕获的异常。我在try块中有一个未打印的测试打印,因此try块不工作。我理解为什么我得到了NPE,但不理解为什么try块不工作。您作为文件位置传递给程序的值是多少?请参阅我的绝对路径答案谢谢,但这不是我主要关心的问题。我真的希望能够从文本文件中读取。而且,这对我不起作用。I get:token finally上出现语法错误,仅同步无效。您能否复制粘贴此代码并粘贴您获得的o/p。,很抱歉,我一定错过了这个。我的程序的src文件夹中有这个文件,但它不工作。你能告诉我程序存在的位置和文件存在的位置吗?它们都存在于Eclipse src文件夹中,位于C:\Users\John\Google Drive\School\CSE 205\PayBills\src。你能解释一下吗?我不知道你在这里是什么意思。我将如何实现这一点?编辑我的答案以解释如果您只传递文件名,代码将查找项目文件夹中的文件,而不是java类所在的文件夹中的文件。好的,这非常有用。一旦我让程序运行起来,我就会实现它。但是,即使文件与类位于同一文件夹中,我仍然存在问题。这将不起作用,因为正如我所说的,如果只传递文件名,代码将在项目文件夹中查找文件,而不是在java类所在的文件夹中。所以如果你
要从您的源文件夹中读取文件,请使用如下文件file=new Filesrc/com/test/abc.txt;请不要忘记接受并投票answer@Johnny请参阅我的更新以解决您的FileNotFoundException。
fr = new FileReader(new File(System.getProperty("home.dir"), filename));
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();
  }
}