为什么我收到错误消息“尝试从文本文件读取时,java 代码中出现未报告的异常 Java.io”?

发布于 2024-12-10 19:48:27 字数 4479 浏览 0 评论 0原文

我是java新手,但仍然遇到问题。

我编写了从文本文件中读取所有数据的代码。它编译正常,但是当我尝试实例化另一个类的代码时,它给出以下错误:

“未报告的异常 java.io.fileNotFoundException,必须捕获或声明为抛出”。

我知道它们可能是我的 throws try catch 的问题,我有和没有包括,但我真的不知道如何使用这些,我会很感激一些帮助。

感谢所有可以提供帮助的人

这是代码

    import java.io.*;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.*;
    import java.util.Scanner;

    public class readTextFile1
    {
        private static int index = 0;
        private static int numberOfDepartmentsToRead;
        private static int i;

        private static  ArrayList<Employee> allEmployees = new ArrayList<Employee>();


        public readTextFile1()
            throws FileNotFoundException
            {

                Scanner inFile = new Scanner (new File("startup.txt") );

                storageSystem theStorageSystem = new storageSystem();       

                numberOfDepartmentsToRead = inFile.nextInt();

                String depName      = inFile.nextLine();
                System.out.println("this is the first one "+depName);

                while  (index < numberOfDepartmentsToRead ) 
                {

                    String depName1    = inFile.nextLine();
                    System.out.println("this should be the department name"+depName1);
                    String location1     = inFile.nextLine();
                    System.out.println("this should be the location"+location1);
                    String numberOfEmps = inFile.nextLine();
                    int    numberOfEmps1 = Integer.parseInt(numberOfEmps);
                    System.out.println("this is the number of employees: "+numberOfEmps1);
                    Department newDepartment = new Department(depName1 , location1);
                    theStorageSystem.setDepartment(newDepartment);

                    while (i < numberOfEmps1 )
                    {
                        String fName     = inFile.nextLine();
                        System.out.println("his first name is: "+fName);
                        String lName     = inFile.nextLine();
                        System.out.println("his last name is"+ lName);
                        String gender    = inFile.nextLine();
                        System.out.println("his gender is: "+gender);
                        String address   = inFile.nextLine();
                        System.out.println("his adrs is: "+address);
                        String   payLevel  = inFile.nextLine(); 
                        System.out.println("and this is the pay level"+payLevel);
                        int dPayLevel = Integer.parseInt(payLevel);
                        Employee employeesFromList = new Employee(fName, lName, gender, dPayLevel, "1er-543");
                        theStorageSystem.setEmployee(employeesFromList);
                        i++;
                    }   
                    i = 0;
                 index++;   
                }

                        while (inFile.hasNextLine())
                        {
                            String fName     = inFile.nextLine();
                                System.out.println("his first name is: "+fName);
                                String lName     = inFile.nextLine();
                                System.out.println("his last name is"+ lName);
                                String gender    = inFile.nextLine();
                                System.out.println("his gender is: "+gender);
                                String address   = inFile.nextLine();
                                System.out.println("his adrs is: "+address);
                                String   payLevel  = inFile.nextLine(); 
                                System.out.println("and this is the pay level"+payLevel);
                                int dPayLevel = Integer.parseInt(payLevel);
                                Employee employeesFromList = new Employee(fName, lName, gender, dPayLevel, "1er-543");
                                theStorageSystem.setEmployee(employeesFromList);
                            //  allEmployees = theStorageSystem.getEmployee();  
                        }

                        }

                    public ArrayList<Employee> giveEmployeeTf()
                    {
                        return allEmployees;
                    }
        }

I'm new to java and I'm still having issues.

I have written code that reads all its data from a text file. It compiles okay but when I try and instantiate the the code from another class it gives me the following error:

"unreported exception java.io.fileNotFoundException, must be caught or declared to be thrown".

I understand that their are probably issues with my throws try catch that I have and have not included but I dont really know how to use these and I would appreciate some assistance with it.

Thanks everyone who can help

This is the code

    import java.io.*;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.*;
    import java.util.Scanner;

    public class readTextFile1
    {
        private static int index = 0;
        private static int numberOfDepartmentsToRead;
        private static int i;

        private static  ArrayList<Employee> allEmployees = new ArrayList<Employee>();


        public readTextFile1()
            throws FileNotFoundException
            {

                Scanner inFile = new Scanner (new File("startup.txt") );

                storageSystem theStorageSystem = new storageSystem();       

                numberOfDepartmentsToRead = inFile.nextInt();

                String depName      = inFile.nextLine();
                System.out.println("this is the first one "+depName);

                while  (index < numberOfDepartmentsToRead ) 
                {

                    String depName1    = inFile.nextLine();
                    System.out.println("this should be the department name"+depName1);
                    String location1     = inFile.nextLine();
                    System.out.println("this should be the location"+location1);
                    String numberOfEmps = inFile.nextLine();
                    int    numberOfEmps1 = Integer.parseInt(numberOfEmps);
                    System.out.println("this is the number of employees: "+numberOfEmps1);
                    Department newDepartment = new Department(depName1 , location1);
                    theStorageSystem.setDepartment(newDepartment);

                    while (i < numberOfEmps1 )
                    {
                        String fName     = inFile.nextLine();
                        System.out.println("his first name is: "+fName);
                        String lName     = inFile.nextLine();
                        System.out.println("his last name is"+ lName);
                        String gender    = inFile.nextLine();
                        System.out.println("his gender is: "+gender);
                        String address   = inFile.nextLine();
                        System.out.println("his adrs is: "+address);
                        String   payLevel  = inFile.nextLine(); 
                        System.out.println("and this is the pay level"+payLevel);
                        int dPayLevel = Integer.parseInt(payLevel);
                        Employee employeesFromList = new Employee(fName, lName, gender, dPayLevel, "1er-543");
                        theStorageSystem.setEmployee(employeesFromList);
                        i++;
                    }   
                    i = 0;
                 index++;   
                }

                        while (inFile.hasNextLine())
                        {
                            String fName     = inFile.nextLine();
                                System.out.println("his first name is: "+fName);
                                String lName     = inFile.nextLine();
                                System.out.println("his last name is"+ lName);
                                String gender    = inFile.nextLine();
                                System.out.println("his gender is: "+gender);
                                String address   = inFile.nextLine();
                                System.out.println("his adrs is: "+address);
                                String   payLevel  = inFile.nextLine(); 
                                System.out.println("and this is the pay level"+payLevel);
                                int dPayLevel = Integer.parseInt(payLevel);
                                Employee employeesFromList = new Employee(fName, lName, gender, dPayLevel, "1er-543");
                                theStorageSystem.setEmployee(employeesFromList);
                            //  allEmployees = theStorageSystem.getEmployee();  
                        }

                        }

                    public ArrayList<Employee> giveEmployeeTf()
                    {
                        return allEmployees;
                    }
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

苦妄 2024-12-17 19:48:27

java中的每个方法都必须声明它可能抛出的异常[除了RuntimeExceptions]。由于您的方法抛出 FileNotFoundException,它必须执行以下两件事之一:

  1. 将其声明为 throws FileNotFoundException

  2. 使用 try,catch 块,并处理此异常。

(*)上面指的是构造函数的激活,即实际激活构造函数的方法。

Every moethod in java must declare the exceptions it might throw [except RuntimeExceptions]. Since your method throws FileNotFoundException, it must do one of 2 things:

  1. declare it as throws FileNotFoundException

  2. use a try,catch block, and handle this exception.

(*)The above is referring to the activation of your constructor, i.e. the method that is actually activating the c'tor.

黄昏下泛黄的笔记 2024-12-17 19:48:27

您可能应该将 readTextFile1() 方法的使用包含在 try-catch 块中:

readTextFile1 cls = new readTextFile1();

try
{
    cls.readTextFile1();
}
catch (FileNotFoundException e)
{
    // report error or something
}

此外,您的类命名错误,因为它没有描述其用途;它似乎存储了 Employee 对象的列表,并使用此方法读取该数据。您最好调用类 DepartmentReader 或其他名称(注意前导大写字母)。

You should probably surround your use of the readTextFile1() method within a try-catch block:

readTextFile1 cls = new readTextFile1();

try
{
    cls.readTextFile1();
}
catch (FileNotFoundException e)
{
    // report error or something
}

Additionally your class is misnamed as it doesn't describe its use; it appears to store a list of Employee objects and reads that data using this method. You would do better to call the class DepartmentReader or something (note the leading uppercase letter).

韵柒 2024-12-17 19:48:27

如果代码中可能出现异常,您有两个选择:

  • 捕获它们(并可选择处理它们)或
  • 重新抛出它们。

捕获它们是通过以 try{} 开头并以 catch(Exceptiontype exceptionname) 结尾的块(带有可选的 finally{} 块)来完成的。

将它们进一步向上抛出意味着您让调用堆栈进一步向上处理异常。为此,您使用短语“抛出 FileNotFoundException”定义了您的类。这意味着从现在开始,在任何代码中使用此方法都需要再次通过捕获它或进一步抛出它来确认此可选异常。

因此,每当您使用上述方法时,您都需要执行上述两件事之一,我确信您错过了这两件事。

If exceptions are possible in your code, you have two options:

  • Catch them (and optionally handle them) or
  • rethrow them.

Catching them is done by blocks starting with try{} and ending in catch(Exceptiontype exceptionname) (with optional finally{} block).

Throwing them further up means that you let the calling stack further up handle the exception. For this purpose, you defined your class with the phrase "throws FileNotFoundException". This means that from now on, using this method in any code will need to acknowledge this optional exception, again either by catching it or throwing it further up still.

So whenever you use the method above, you need to do one of the two mentioned things, and I'm sure you missed both.

酷到爆炸 2024-12-17 19:48:27

您可能需要阅读异常和异常处理


        public readTextFile1()
            throws FileNotFoundException

这声明 readTextFile1 可以抛出 FileNotFoundException,这是所谓的检查异常。这意味着,在调用此方法时,您必须要么捕获它,要么显式声明调用方法也可以抛出此异常。

抓住它就可以这样了:(

readTextFile1 file = new readTextFile1();
try {
    readTextFile1.readTextFile1();
} catch (FileNotFoundException ex) {
    // Here, handle the case that the file is not found. For example:
    System.err.println("File not found");
}

顺便说一句,Java中的类名通常用大写字母书写,并且应该采用名词形式,而不是动词形式。例如,TextFileReader。)

You might want to read up on exceptions and exception handling.


        public readTextFile1()
            throws FileNotFoundException

This declares that readTextFile1 can throw FileNotFoundException, which is a so-called checked exception. That means that, at the point you call this method, you must either catch it, or explicitly declare that the calling method can also throw this.

Catching it would work thusly:

readTextFile1 file = new readTextFile1();
try {
    readTextFile1.readTextFile1();
} catch (FileNotFoundException ex) {
    // Here, handle the case that the file is not found. For example:
    System.err.println("File not found");
}

(By the way, class names in Java are usually written with a capital letter, and should be in the form of a noun, not a verb. For example, TextFileReader.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文