简体   繁体   English

我正在尝试打开我的文本文件,但我不知道问题出在哪里

[英]I am trying to open my text file but I do not know what the issue is

I am trying to make a program that takes in a students id number, first and last name along with their class grade.我正在尝试制作一个程序,该程序接收学生的 ID 号、名字和姓氏以及他们的班级成绩。 After I want to be able to read the data.在我希望能够读取数据之后。 But I am getting an error when I try to read the data ( or open the file).但是当我尝试读取数据(或打开文件)时出现错误。 When I run the program I get "Error opening file".当我运行程序时,我收到“打开文件时出错”。 I have 5 classes and will attach them.我有 5 个课程并将附加它们。 Could someone try to help me out and find out what is wrong.有人可以尝试帮助我并找出问题所在。 I will attach the classes:我将附上课程:

    public class StudentRecords 
    {
        private int IDnumber;
        private String firstName;
        private String lastName;
        private double grade;

       public StudentRecords()
       {
            this( 0, "", "", 0.0);

        }

        public StudentRecords( int id, String first, String last, double gr )
        {
            setIDnumber( id );
            setFirstName( first);
            setLastName( last );
            setGrade( gr );
        }
        public void setIDnumber( int id)
        {
            IDnumber = id;
        }

        public int getIDnumber()
        {
            return IDnumber;
        }

         public void setFirstName( String first )
        {
            firstName = first;
        }

        public String getFirstName()
        }
            return firstName;
        }

        public void setLastName( String last)
        {
            lastName = last;
        }

        public String getLastName()
        {
            return lastName;
        }

        public void setGrade( double gr)
        {
            grade = gr;
        }

        public double getGrade()
        {
            return grade;

        }
    }

Here is the second class这是第二堂课

    import java.io.FileNotFoundException;
    import java.lang.SecurityException;
    import java.util.Formatter;
    import java.util.FormatterClosedException;
    import java.util.NoSuchElementException;
    import java.util.Scanner;

    public class StudentTextFile 
    {
        private Formatter output;

        public void openFile()
        {
            try
            {
                output = new Formatter( "students.txt");
            }
            catch ( SecurityException securityException )
            {
                System.err.println(
                    "You do not have write access to this file.");
                System.exit(1);

            }
            catch ( FileNotFoundException fileNotFoundException )
            {
                System.err.println( "Error opening or creating file." );
                System.exit(1);
            }
        }

        public void addStudentRecords()
        {
            StudentRecords record = new StudentRecords();
            Scanner input = new Scanner( System.in);

            System.out.printf("%s\n%s\n%s\n%s\n\n",
            "To terminate input, type the end-of-file indicator",
            "when you are prompted to enter input.",
            "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
            "On Windows type <crtl> z then press enter");

            System.out.printf( "%s\n%s",
        "Enter student ID number (> 0), first name, last name and grade. ",
            "? ");

            while ( input.hasNext() )
            {
                try
                {
                    record.setIDnumber( input.nextInt());
                    record.setFirstName( input.next());
                    record.setLastName(input.next());
                    record.setGrade( input.nextDouble());

               if ( record.getIDnumber() > 0 )
               {
                    output.format( "%d %s %s %.2f\n", record.getIDnumber(),
                    record.getFirstName(), record.getLastName(), 
                record.getGrade() );
                }
                 else
                {
                System.out.println(
                        "Student ID Number must be greater than 0.");
            }
        }
        catch ( FormatterClosedException formatterClosedException)
        {
            System.err.println( "Error writing to file.");
            return;
        }
        catch ( NoSuchElementException elementException)
        {
            System.err.println( "Invalid input. Please try again.");
            input.nextLine();

        }
        System.out.printf( "%s %s \n%s", "Enter student ID number (>0),",
                "first name. last name and grade.", "? ");
    }
}
public void closeFile()
{
    if ( output != null )
        output.close();
}

} }

Here is the third class这是第三节课

    public class StudentTextFileTest {

        public static void main(String[] args) 
        {

            StudentTextFile application = new StudentTextFile();

            application.openFile();
            application.addStudentRecords();
            application.closeFile();

        }

    }   

Here is the fourth class这是第四节课

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.lang.IllegalStateException;
    import java.util.NoSuchElementException;
    import java.util.Scanner;

    public class ReadStudentTextFile 
    {
        private Scanner input;

        public void openfile()
        {
            try
            {
                input = new Scanner( new File( "studentrecords.txt"));
            }
            catch ( FileNotFoundException fileNotFoundException )
            {
                System.err.println( "Error opening file.");
                System.exit(1);

            }
        }

        public void readStudentRecords()
        {
            StudentRecords record = new StudentRecords();

            System.out.printf( "%-10s%-12s%-12s%10s\n", "Student ID Number",
            "First Name", "Last Name", "Balance");

        try 
        {
            while ( input.hasNext())
            {
                record.setIDnumber( input.nextInt());
                record.setFirstName( input.next() );
                record.setLastName( input.next());
                record.setGrade( input.nextDouble());

                System.out.printf( "%-10d%-12s%-12s%10.2f\n",
                record.getIDnumber(), record.getFirstName(),
                record.getLastName(), record.getGrade() );
            }
        }
        catch ( NoSuchElementException elementException )
        {
            System.err.println( "File improperly formed. ");
            input.close();
            System.exit(1);

        }
         catch ( IllegalStateException stateException)
        {
            System.err.println(" Error reading from file.");
            System.exit(1);
        }
        }
        public void closeFile()
        {
            if (input!= null )
                input.close();
        }
     }

Here is the fifth class这是第五课

     public class ReadStudentTextFileTest 
    {

        public static void main(String[] args) 
        {

            ReadStudentTextFile application = new ReadStudentTextFile();

            application.openfile();
            application.readStudentRecords();
            application.closeFile();



        }

    }

I second trying to put the whole path instead.我第二次尝试将整个路径改为。

For relative paths, if you're doing compiling and running in command line/terminal, you need to have that studentrecords.txt in the same directory of your code files.对于相对路径,如果您在命令行/终端中进行编译和运行,则需要将 studentrecords.txt 放在代码文件的同一目录中。

If you're using an IDE, you need to put your studentrecords.txt under the src/ folder.如果您使用的是 IDE,则需要将 studentrecords.txt 放在 src/ 文件夹下。 This is assuming you're not in maven project setup;这是假设您不在 maven 项目设置中; otherwise it should be put under /src/main/java/resources/ .否则它应该放在 /src/main/java/resources/ 下。

Hope this helps!希望这可以帮助!

Instead of creating a file every time you read from it, you should try using a FileReader wrapped in a BufferedReader.与其每次读取文件时都创建一个文件,不如尝试使用包装在 BufferedReader 中的 FileReader。

Change this:改变这个:

input = new Scanner( new File( "studentrecords.txt"));

To:到:

input = new Scanner(new BufferedReader(new FileReader("studentrecords.txt")));

See the tutorial for the Scanner class for more info.有关更多信息,请参阅Scanner 类教程

Also make sure that the file you're trying to read from exists.还要确保您尝试读取的文件存在。 That is, it should be on the same folder as your code.也就是说,它应该与您的代码位于同一文件夹中。 Another easy option is to try providing the full path to the file.另一个简单的选择是尝试提供文件的完整路径。

暂无
暂无

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

相关问题 我正在尝试实现自己的HashSet,但我不知道应该返回什么iterator()方法? - I am trying to implement my own HashSet and I do not know what iterator() method should return? 我的尝试捕获..很奇怪,我怎么知道我正在写文件 - my try catch.. is being weird and how do i know i am writing a file 我怎么知道我正在使用什么 jaxrs 实现? - How do I know what implementation of jaxrs I am using? 我正在尝试将文件作为参数发送给方法,但不知道如何发送? - I am trying to send File as a parameter to a method but dont know how? 我正在尝试给我的扫描仪打电话,但它不起作用。 我该怎么办? - I am trying to call my Scanner but its not working. What should i do? 我试图递归地对我的普通树做一个插入方法,我该怎么办? - i am trying to make an insert method recursively to my general tree what should i do? 为什么我的程序找不到我要扫描的文本文件? - Why can't my program find my text file I am trying to scan? 我正在为我的班级使用 java 在 JGrasp 中制作一个神奇的 8 球。 如何让我的代码运行? 我不知道我的错误是什么或如何解决它? - I am working on making a magic 8 ball in JGrasp using java for my class. how do I get my code to run? I do not know what my error is or how to fix it? 我想在我的maven设置xml中设置两个镜像,需要帮助不知道我在这里做错了什么 - I want to setup two mirrors in my maven settings xml, need help do not know what i am doing wrong here 我的代码中有什么错误? 我想从 2 天开始理解它? - what is the error in my code? I am trying to understand it from 2 days?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM