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

标签 java function io text-files

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

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/

相关文章:

java - 如何在某些测试端点 "application_id"中注入(inject) "/v1/random-session/{id}/submit"?

python - 我的战舰代码缺乏定义的问题

c - C select() 函数是否已弃用?

c# - 如何在 asp.net 中按顺序从目录中获取文件?

java - Quickblox android 聊天 - 音频附件上传失败

java - 无需重新部署应用程序即可反射(reflect)更改

java - 卡夫卡收到错误 Bootstrap 服务器中没有给出可解析的 Bootstrap 网址

php - PHP 函数是否区分大小写?

function - 在 postgresql 中运行函数抛出运行时错误

c++ - 如何在 C/C++ 中以编程方式读取 linux 文件权限