gpt4 book ai didi

java - 读取文件中的特定信息

转载 作者:行者123 更新时间:2023-12-02 04:11:19 24 4
gpt4 key购买 nike

我想用Scanner读取这个文件,但不是全部信息,只有分号后面的东西,比如10、warrior、John Smith等等。

currhp: 10

type: Warrior

name: John Smith

items:
Stick,1,2,10,5

gold: 10

type: Wizard

我尝试解决这个问题,但没有成功。

Scanner infile;

Scanner inp = new Scanner(System.in);

try {

infile = new Scanner(new File("player_save.txt"));

} catch (FileNotFoundException o) {

System.out.println(o); return; }

while (infile.hasNextLine()) {

System.out.println(infile.nextLine());

}

最佳答案

您需要打开文件,逐行读取,然后分割每一行并使用您希望对其进行进一步处理的行 block 。

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile{
public static void main(String[] args) throws IOException {
//fix the URL to where your file is located.
try (BufferedReader br = new BufferedReader(new FileReader("C:\\player_save.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(line.length() > 0) {
if(line.contains(":")) {
System.out.println("Before colon >> " + line.split(":")[0]);
} else {
//no column found taking the whole line
System.out.println("whole line having no coln: " + line);
}
}
}
} catch(FileNotFoundException fnfe) {
//Handle scenario where the file does not exist
} catch(IOException ie) {
//Handle other File I/O exceptions here
}
}
}

关于java - 读取文件中的特定信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33761190/

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