Java:基于行首的文件读取行

时间:2015-07-31 11:42:53

标签: java file io

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

我打算做的是将某些程序设置存储在txt文件中,以便在退出/重新启动程序时快速检索它们。

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

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

:将是分隔符,在程序中我希望能够根据“密钥”(例如“名字”,“姓氏”等)检索特定值。 / p>

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

4 个答案:

答案 0 :(得分:4)

看看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);

注意:如果要在属性键中使用空格,则必须将其转义。例如:

First\ Name: Stef

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

答案 1 :(得分:1)

  

我想要做的是阅读以特定文字开头的特定行。

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

答案 2 :(得分:0)

您可以使用Properties从文件中检索密钥和值 使用Properties

从文本文件中读取数据
            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
            }

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

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

答案 3 :(得分:0)

使用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
相关问题