gpt4 book ai didi

java - 读取具有特定格式的文本文件

转载 作者:行者123 更新时间:2023-12-02 02:52:37 26 4
gpt4 key购买 nike

我正在寻找一些有关如何读取具有特定格式的文本文件并将它们分配给程序中的变量的帮助。

TextFile.txt

//Variables
start={x}
forward={c}
end={y}
pause={p}
path={x, c, c, c, c, p, c, c, y}

类.java

public void readFile()
{

char start, forward, end, pause;

BufferedReader reader =
new BufferedReader (
new InputStreamReader (new FileInputStream (TextFile.txt)));

String line;
while ((line = reader.readLine ()) != null)
{
if (line.startWith ("//") || line.trim ().isEmpty ())
continue; // Ignore the line

//**This is the part I need help with**
}
}

有人可以解释一下如何将文本文件中的值分配给变量吗?

例如,start 等于“x”,forward 等于“c”,等等。

谢谢。

最佳答案

你可以使用这样的东西:

String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("//") || line.trim().isEmpty())
continue;
else if(line.startsWith("start"))
start= line.charAt(line.indexOf("{")+1);
else if(line.startsWith("forward"))
forward= line.charAt(line.indexOf("{")+1);
else if(line.startsWith("end"))
end= line.charAt(line.indexOf("{")+1);
else if(line.startsWith("pause"))
pause= line.charAt(line.indexOf("{")+1);
else if(line.startsWith("path"))
for(String s: line.substring(line.indexOf("{")+1, line.indexOf("}")).split(", "))
path.add(s.charAt(0));

这假设您的路径定义为 LinkedList<Character> path = new LinkedList<>(); .

关于java - 读取具有特定格式的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43572612/

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