简体   繁体   English

java如何将文本文件读入数组?

[英]How to read text file into an array, java?

How can I read a text file into the waitingRoom array?如何将文本文件读入waitingRoom 数组? I need to also be able to use this file to add and remove passengers?我还需要能够使用此文件添加和删除乘客吗? Can anyone help x任何人都可以帮助 x

package trainstation;

import java.util.Scanner;

public class TrainStation 
{

    static int WAITING_ROOM_CAPACITY = 30;

    private static Passenger[] waitingRoom = new Passenger[WAITING_ROOM_CAPACITY];
    private static PassengerQueue trainQueue = new PassengerQueue();


    public static void main(String[] args) 
    {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);

while (myReader.hasNextLine()) {

  String data = myReader.nextLine();  // The data of the txt file will depends on the format you wanted.
  System.out.println(data); // Or you can append data to an array ...

}

Or if your txt file data format is something like this或者如果你的txt文件数据格式是这样的

Name |姓名 | Lastname |姓氏 | 1 Name1 | 1 姓名1 | Lastname1 |姓氏1 | 2 2

Then you have to split each line of data in your txt file by a delimeter..然后你必须用分隔符分割 txt 文件中的每一行数据。

File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);

while (myReader.hasNextLine()) {

  String[] data = (myReader.nextLine()).split(" | "); // It is already an array
  System.out.println(data); // Or you can append data to an array ...

}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM