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