gpt4 book ai didi

java - 如何从文本文件中读取数据并将其中的一些数据保存到数组中

转载 作者:行者123 更新时间:2023-11-29 08:09:41 25 4
gpt4 key购买 nike

我的计算机中有一个文本文件,我正在从我的 Java 程序中读取它,我想建立一些标准。这是我的记事本文件:

   #Students
#studentId studentkey yearLevel studentName token
358314 432731243 12 Adrian Afg56
358297 432730131 12 Armstrong YUY89
358341 432737489 12 Atkins JK671

#Teachers
#teacherId teacherkey yearLevel teacherName token
358314 432731243 12 Adrian N7ACD
358297 432730131 12 Armstrong EY2C
358341 432737489 12 Atkins F4NGH

当我从这个记事本文件中读取时,我得到了与我的应用程序中一样的准确数据但我只想读取 students 中的 token 列并将它们放入我名为学生代币。这是代码

public static void main(String[] args) {
ArrayList<String > studentTokens = new ArrayList<String>();

try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("c:/work/data1.txt");

// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;

//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}

//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}

最佳答案

一个小提示:

private static Integer STUDENT_ID_COLUMN = 0;
private static Integer STUDENT_KEY_COLUMN = 1;
private static Integer YEAR_LEVEL_COLUMN = 2;
private static Integer STUDENT_NAME_COLUMN = 3;
private static Integer TOKEN_COLUMN = 4;

public static void main(String[] args) {

ArrayList<String> studentTokens = new ArrayList<>();

try (FileInputStream fstream = new FileInputStream("test.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fstream);
BufferedReader br = new BufferedReader(inputStreamReader)) {

String strLine;

// Read File Line By Line
while ((strLine = br.readLine()) != null) {

strLine = strLine.trim();

if ((strLine.length() != 0) && (strLine.charAt(0) != '#')) {
String[] columns = strLine.split("\\s+");
studentTokens.add(columns[TOKEN_COLUMN]);
}

}
}
catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
return;
}

for (String s : studentTokens) {
System.out.println(s);
}
}

以上代码不是完整的解决方案。它提取所有标记(针对学生和教师)。我希望你能设法让它从那时起只对学生代币起作用......

关于java - 如何从文本文件中读取数据并将其中的一些数据保存到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8877483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com