Java 读取逗号分隔的配置文件的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/684131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:53:35  来源:igfitidea点击:

What is the best way to read a comma delimited configuration file?

javafile-io

提问by

I have a comma delimited configuration file. The empty lines are ignored and there need to be errors on invalid lines:

我有一个逗号分隔的配置文件。空行被忽略,无效行需要有错误:

foo,bar

foo2, bar3

富,酒吧

foo2, bar3

I want to read this file into a HashMapwhere the key (foo) is mapped with a value (bar).

我想将此文件读入一个HashMap键(foo)与值(bar)映射的地方。

What is the best way to do this?

做这个的最好方式是什么?

采纳答案by TofuBeer

If you can use x = y instead of x, y then you can use the Properties class.

如果您可以使用 x = y 而不是 x, y 那么您可以使用 Properties 类。

If you do need to have x, y then look at the java.util.Scanneryou can set the delimiter to use as a separator (the javadoc shows examples of doing that).

如果您确实需要 x, y 然后查看java.util.Scanner您可以将分隔符设置为用作分隔符(javadoc 显示了这样做的示例)。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

class Main
{
    public static void main(final String[] argv)
    {
        final File file;

        file = new File(argv[0]);

        try
        {
            final Scanner scanner;

            scanner = new Scanner(file);

            while(scanner.hasNextLine())
            {
                if(scanner.hasNext(".*,"))
                {
                    String key;
                    final String value;

                    key = scanner.next(".*,").trim();

                    if(!(scanner.hasNext()))
                    {
                        // pick a better exception to throw
                        throw new Error("Missing value for key: " + key);
                    }

                    key   = key.substring(0, key.length() - 1);
                    value = scanner.next();

                    System.out.println("key = " + key + " value = " + value);
                }
            }
        }
        catch(final FileNotFoundException ex)
        {
            ex.printStackTrace();
        }
    }
}

and the Properties version (way simpler for the parsing, as there is none)

和属性版本(解析方式更简单,因为没有)

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Properties;

class Main
{
    public static void main(final String[] argv)
    {
        Reader reader;

        reader = null;

        try
        {
            final Properties properties;

            reader = new BufferedReader(
                            new FileReader(argv[0]));
            properties = new Properties();
            properties.load(reader);
            System.out.println(properties);
        }
        catch(final IOException ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            if(reader != null)
            {
                try
                {
                    reader.close();
                }
                catch(final IOException ex)
                {
                    ex.printStackTrace();
                }
            }
        }
    }
}

回答by Jon

Your best bet is to use the java.util.Scanner class to read in the values in the config file, using the comma as a delimiter. Link here to the Javadoc:

最好的办法是使用 java.util.Scanner 类读取配置文件中的值,并使用逗号作为分隔符。在此处链接到 Javadoc:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html

Example would be:

示例是:

Scanner sc = new Scanner(new File("thing.config"));
sc.useDelimiter(",");
while (sc.hasNext()) {
   String token = sc.next();
}

回答by TechTravelThink

try {
  BufferedReader cfgFile = new BufferedReader(new FileReader(new File("config.file")));
  String line = null;

  // Read the file line by line
  while ((line = cfgFile.readLine()) != null) {
    line.trim();
    // Ignore empty lines
    if (!rec.equals("")) {
       String [] fields = line.split(","); 
       String key = fields[0];
       String value = fields[1];  
       // TODO: Check for more than 2 fields
       // TODO: Add key, value pair to Hashmap  
    } // if
  } // while

  cfgFile.close();
} catch (IOException e) {
  System.out.println("Unexpected File IO Error");
}

回答by Nick

I personally use a jar by a guy named Stephen Ostermiller, which is his Labeled CSVparser. Here is some sample code.

我个人使用了一个名叫 Stephen Ostermiller 的人的 jar,这是他的Labeled CSV解析器。这是一些示例代码。

LabeledCSVParser lcsvp = new LabeledCSVParser(
    new CSVParser(
        new StringReader(
            "Name,Phone\n" +
            "Stewart,212-555-3233\n" +
            "Cindy,212-555-8492\n"
        )
    )
);

while(lcsvp.getLine() != null){
    System.out.println(
        "Name: " + lcsvp.getValueByLabel("Name")
    );
    System.out.println(
        "Phone: " + lcsvp.getValueByLabel("Phone")
    );
}