Java: 根据行首从文件中读取行

Java: Read Line From File Based on Start of Line

我知道如何使用 Java 读取文件。我想要做的是阅读以特定文本开头的特定行。

我打算做的是将某些程序设置存储在一个 txt 文件中,以便在我 exit/restart 编程时可以快速检索它们。

例如,文件可能如下所示:

First Name: John
Last Name: Smith
Email: JohnSmith@gmail.com
Password: 123456789 

: 将是分隔符,在程序中我希望能够根据 "key" 检索特定值(例如 "First Name"、"Last Name"等等)。

我知道我可以将它存储到数据库中,但我想快速编写它来测试我的程序,而无需经历将其写入数据库的麻烦。

What I want to do is read a specific line which starts with specific text.

从文件开头读取,跳过所有不需要的行。没有更简单的方法。您可以为文件编制索引以便快速访问,但您至少已扫描文件一次。

看看java.util.Properties。它会完成您在这里要求的一切,包括解析文件。

示例代码:

    File file = new File("myprops.txt");
    Properties properties = new Properties();

    try (InputStream in = new FileInputStream (file)) {
         properties.load (in);
    }

    String myValue = (String) properties.get("myKey");
    System.out.println (myValue);

注意:如果您想在 属性 键中使用 space,则必须将其转义。例如:

First\ Name: Stef

Here 是有关属性文件语法的文档。

您可以使用 Properties 从文件中检索键和值。
使用 Properties class

从文本文件读取数据
            File file = new File("text.txt");
            FileInputStream fileInput = new FileInputStream(file);
            Properties properties = new Properties();
            properties.load(fileInput);
            fileInput.close();

            Enumeration enuKeys = properties.keys();
            while (enuKeys.hasMoreElements()) {
                String key = (String) enuKeys.nextElement();
                String value = properties.getProperty(key);//with specific key
                System.out.println(key + ": " + value);//both key and value
            }

您可以根据key检索特定的value

   System.out.println(properties.getProperty("Password"));//with specific key

使用 Java 8,您还可以通过这种方式将文件读入地图:

        Map<String, String> propertiesMap = Files.lines(Paths.get("test.txt")) // read in to Stream<String>
            .map(x -> x.split(":\s+")) // split to Stream<String[]> 
            .filter(x->x.length==2) // only accept values which consist of two values
            .collect(Collectors.toMap(x -> x[0], x -> x[1])); // create map. first element or array is key, second is value