Java无法从文件读取 [英] Java Cannot Read From File

查看:121
本文介绍了Java无法从文件读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Java程序,该程序可以接收用户输入并将其保存到ArrayList中,然后使用ArrayList打开一系列网页。该程序还应该能够从文件中读取网址。我在这里遇到问题。

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.

我目前正在接受:找不到bills.txt文件。 //文件位于我的src文件夹中

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

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

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.

推荐答案

如果您只是通过文件名,那么您必须在读取文件之前附加文件的位置

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

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

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

此abc.txt文件应位于 C:/ opt / files /

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

记住,我添加了驱动器名称,因为您试图运行main

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.

希望这会有所帮助。

这篇关于Java无法从文件读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆