How do I read in a line from a .dat file in Java t

2019-07-13 02:35发布

问题:

I am attempting to read a .dat file using Java in TextPad. The .dat file has multiple lines of code but each line has separate pieces of information that I need for different methods in my main method and object classes. How do I separate the information provided in the file and input the separate pieces into any of my classes?

I know how to read basic input from a .txt file but it is not working with the .dat file. I do not know how to separate data that does not have commas, and I am not allowed to change the data in the .dat file.

When viewing the .dat file in TextPad it shows up as standard characters, not as binary. The code I am trying to read is below:

1001Intro. to CompSci 4ALBERT, PETER A. Comp Info System A 1001Intro. to CompSci 4ALLENSON, SHEILA M. Comp Info System B 1001Intro. to CompSci 4ANDERSON, ALENE T. Comp Info System A 1001Intro. to CompSci 4HENDRIX, JAMES D. Lib Arts - MIS C 1001Intro. to CompSci 4CANNON, FREDDY B.B. Comp Info System B 1002Visual Basic 3ALBERT, PETER A. Comp Info System C 1002Visual Basic 3ALLENSON, SHEILA M. Comp Info System D 1002Visual Basic 3ANDERSON, ALENE T. Comp Info System A 1002Visual Basic 3HENDRIX, JAMES D. Lib Arts - MIS B 1002Visual Basic 3CANNON, FREDDY B.B. Comp Info System B 1003Cisco Networking I 4ALBERT, PETER A. Comp Info System C 1003Cisco Networking I 4ALLENSON, SHEILA M. Comp Info System A 1003Cisco Networking I 4ANDERSON, ALENE T. Comp Info System A 1003Cisco Networking I 4HENDRIX, JAMES D. Lib Arts - MIS D 1004Cisco Networking III3ALBERT, PETER A. Comp Info System B 1004Cisco Networking III3ALLENSON, SHEILA M. Comp Info System C 1004Cisco Networking III3ANDERSON, ALENE T. Comp Info System A 1004Cisco Networking III3CANNON, FREDDY B.B. Comp Info System B 1004Cisco Networking III3HELLER, HELEN H. Lib Arts - MIS A 1004Cisco Networking III3HENDRIX, JAMES D. Lib Arts - MIS F

The individual pieces of information are labeled below using line 1 from above as an example:

CourseID CourseName Credits StudentName Major Grade

1001Intro. to CompSci 4ALBERT, PETER A. Comp Info System A

回答1:

Note: This answer assumes that each column is a definite length (4-digit course ID, 20-character course name, 1-digit credits, 20-character student name, 20-character major, 1-digit grade)

First, you'll want to get a list of every line in the file.

String[] lines = Files.readAllLines(new File("myfile.dat").toPath()).toArray(new String[0]);

Next, process each line by using the substring() method:

for(String line: lines) {
    int courseId = Integer.parseInt(line.substring(0, 4));
    String studentName = line.substring(4, 24).trim();
    // etc...
}

The trim() function removes trailing whitespace.



回答2:

File file = new File("xyz.dat");
Scanner scnr = new Scanner(file);
while(scnr.hasNextLine()){
   String line = scnr.nextLine();
   System.out.println(line);
}

There is no simple way of doing it as there is no delimiter to separate strings. Try a hack like if data starts with number then its a course id, if a comma is there between two words it's a name and so on...



回答3:

I realize this post already has an accepted answer but I just wanted to address some other concerns the OP has made within his comments.

Below I have provided runnable code which demonstrates how to retrieve the data from a Multiple Fixed Field Length data file. The code is based from what @kittycat3141 had provided since this is the way to go with this particular situation (in my honest opinion).

In your comments Chris, you made note of how to locate and retrieve data not for just all students but for specific students as well. The code example I provided below does just that by way of utilizing the String.contains() method. By using this method we can either use the full student name or just part of the student name. When doing a student search letter case is also ignored since for some data files the case may be camel rather that all uppercase which seems to be the case in your particular data file.

The runnable class utilizes the Scanner object for collecting information from console User input with regards to: path and file name to data file, display all students, or data for a specific student. If nothing is supplied then the code run-time terminates. The input is in a loop so that more that one student query can be made.

The code was written so as to be easy to follow. When you run the code look at the output console and answer the displayed prompts. Here is the code. I hope someone finds this somewhat useful:

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class ReadDatFile {
    private static String[] dataLines;

    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
        String studentName = "";

        System.out.println("Please enter the path and file name to data file:");
        String filePath = userInput.nextLine();
        if ("".equals(filePath)) { System.exit(0); }
        fillDataArray(filePath);

        do {
            System.out.println("\nEnter 'ALL' to display all Student data or\n"
                             + "enter a Student name to return data for.\n"
                             + "(To exit enter nothing): -> ");
            studentName = userInput.nextLine();
            if ("".equals(studentName)) { System.exit(0); }
            if ("all".equals(studentName.toLowerCase())) {
                displayAllStudents();
            }
            else { 
                displayStudent(studentName); 
            }
        } while (!"".equals(studentName));
    }

    private static void fillDataArray(String fileName) {
        try {
            dataLines = Files.readAllLines(new File(fileName).toPath()).toArray(new String[0]);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog (null, "Error Accessing The Data File "
                    + "Indicated Below!\n\n" + fileName + "\n\n" + ex.getMessage(), 
                    "FillDataArray() Method Error", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    }

    private static void displayAllStudents() {
        System.out.println("**************  ALL STUDENTS  ***************");
        for (int i = 0; i < dataLines.length; i++) {
            String courseID = dataLines[i].substring(0, 4).trim();
            String courseName = dataLines[i].substring(4, 24).trim();
            String courseCredit = dataLines[i].substring(24, 25).trim();
            String studName = dataLines[i].substring(25, 45).trim();
            String studMajor = dataLines[i].substring(45, 65).trim();
            String studGrade = dataLines[i].substring(65, 66).trim();

            System.out.println("Student Name : " + studName);
            System.out.println("Course ID    : " + courseID);
            System.out.println("Course Name  : " + courseName);
            System.out.println("Course Credit: " + courseCredit);
            System.out.println("Student Major: " + studMajor);
            System.out.println("Student Grade: " + studGrade);
            System.out.println("---------------------------------------------");
        }
        System.out.println("***********  END OF STUDENT DATA  ***********");

    }

    private static void displayStudent(String studentName) {
        System.out.println("********* COURSE DATA FOR " + studentName + " *********");
        ArrayList<String> student = new ArrayList<>();
        for (int i = 0; i < dataLines.length; i++) {
            String studName = dataLines[i].substring(25, 45).trim().toLowerCase();
            if (studName.contains(studentName.toLowerCase())) {
                student.add(dataLines[i]);
            }
        }    

        for (int i = 0; i < student.size(); i++) {
            String courseID = student.get(i).substring(0, 4).trim();
            String courseName = student.get(i).substring(4, 24).trim();
            String courseCredit = student.get(i).substring(24, 25).trim();
            String studName = student.get(i).substring(25, 45).trim();
            String studMajor = student.get(i).substring(45, 65).trim();
            String studGrade = student.get(i).substring(65, 66).trim();

            System.out.println("Student Name : " + studName);
            System.out.println("Course ID    : " + courseID);
            System.out.println("Course Name  : " + courseName);
            System.out.println("Course Credit: " + courseCredit);
            System.out.println("Student Major: " + studMajor);
            System.out.println("Student Grade: " + studGrade);
            System.out.println("---------------------------------------------");
        }
        System.out.println("***********  END OF STUDENT DATA  ***********");
    }
}