简体   繁体   English

Java无法从文件读取

[英]Java Cannot Read From File

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. 我正在编写一个Java程序,该程序可以接收用户条目并将其保存到ArrayList中,然后使用ArrayList打开一系列网页。 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. 我当前正在获取:找不到文件bills.txt。 //the file is in my src folder //文件在我的src文件夹中

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. 编辑:好的,该程序不再崩溃,因为我修复了NPE,但是我仍然收到“找不到文件bills.txt。”,这是捕获的异常。 As stated above, the file is located in my src folder so the path should be correct. 如上所述,该文件位于我的src文件夹中,因此路径应正确。

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 (eg c:/workspace/project/test , if your project name is test and is located at c:/workspace/project) 如果仅将文件名作为参数传递给File构造函数,这将是这种方法的工作方式,它将尝试在/ Project /目录中查找文件(例如c:/ workspace / project / test,如果您的项目名称为test并且为位于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/" 此abc.txt应位于“ C:/ opt / files /”

Remember I have added drive name because you are trying to run main 记住我添加了驱动器名称,因为您正在尝试运行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. 如果仅传递文件名,则代码将在项目文件夹中而不是Java类所在的文件夹中查找文件。

Hope this helps. 希望这可以帮助。

If just have to get out of the error for Null Poninter Exception from this to 如果只是要摆脱Null Poninter Exception的错误,从此到

 finally
                       {
                           inFile.close();
                       }  

to

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

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

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. Java将查找相对于您的工作目录的文件。

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" . 例如,如果要在~/project中执行程序,并且文件位于~/foo ,则需要将"..foo/bills.txt"作为文件路径或等效的"~/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. 如果仅使用bills.txt测试程序,则可以始终将其移至执行程序的目录。

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. 之所以抛出NullPointerException是因为您试图关闭仍未实例化的infile ,因为在try-catch块中可以实例化之前引发的异常。 So You should change: 因此,您应该更改:

finally
{
     inFile.close();
} 

To

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

}

After your NPE is resolved. 解决您的NPE之后。 Here is the way that you could access your "Bill.txt" file. 这是您可以访问“ Bill.txt”文件的方法。 Use this code instead: 请改用以下代码:

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

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. 这里可能不是THE解决方案,但可能可以使用其中的一部分,即JFileChoser,以了解它如何在Stream中移动,希望对您有所帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM