如何从 Java 中的 .dat 文件中读取一行然后需要分隔?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34258810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:29:01  来源:igfitidea点击:

How do I read in a line from a .dat file in Java that then needs to be separated?

javafile-ioinputiooutput

提问by Chris Samuels

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?

我正在尝试在 TextPad 中使用 Java 读取 .dat 文件。.dat 文件有多行代码,但每一行都有单独的信息,我的主方法和对象类中的不同方法需要这些信息。如何分离文件中提供的信息并将单独的部分输入到我的任何类中?

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.

我知道如何从 .t​​xt 文件读取基本输入,但它不适用于 .dat 文件。我不知道如何分隔没有逗号的数据,我不允许更改 .dat 文件中的数据。

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:

在 TextPad 中查看 .dat 文件时,它显示为标准字符,而不是二进制。我正在尝试阅读的代码如下:

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

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:

下面以第 1 行为例对各个信息进行标记:

CourseIDCourseName CreditsStudentName MajorGrade

CourseIDCourseName学分StudentName 专业成绩

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

1001介绍。CompSci 4ALBERT, PETER A. Comp Info SystemA

采纳答案by FlyingPiMonster

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)

注意:此答案假设每一列都有固定长度(4 位课程 ID、20 位课程名称、1 位学分、20 位学生姓名、20 位专业、1 位成绩)

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:

接下来,使用以下substring()方法处理每一行:

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.

trim()函数删除尾随空格。

回答by A J

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...

没有简单的方法可以做到这一点,因为没有分隔符来分隔字符串。尝试一下,如果数据以数字开头,则它是课程 ID,如果两个单词之间有逗号,则它是名称等等......

回答by DevilsHnd

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.

我意识到这篇文章已经有一个可接受的答案,但我只是想解决 OP 在他的评论中提出的其他一些问题。

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

下面我提供了可运行的代码,它演示了如何从多固定字段长度数据文件中检索数据。该代码基于@kittycat3141 提供的内容,因为这是处理这种特殊情况的方法(在我看来)。

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.

在您的评论 Chris 中,您注意到如何定位和检索数据,不仅适用于所有学生,也适用于特定学生。我在下面提供的代码示例正是通过使用 String.contains() 方法来实现的。通过使用这种方法,我们可以使用完整的学生姓名或仅使用学生姓名的一部分。在进行学生搜索字母大小写时,也会忽略大小写,因为对于某些数据文件,大小写可能是驼峰式,而不是所有大写字母,这在您的特定数据文件中似乎是这种情况。

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.

runnable 类利用 Scanner 对象从控制台用户输入中收集信息:数据文件的路径和文件名、显示所有学生或特定学生的数据。如果未提供任何内容,则代码运行时终止。输入处于循环中,以便可以进行不止一个学生的查询。

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  ***********");
    }
}