java 如何读取 key=value 文件以及如何拆分逗号分隔的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2304609/
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-10-29 20:31:04  来源:igfitidea点击:

How to read key=value file and how to split a comma-separated String?

java

提问by user238384

I made a config file it has some following format

我制作了一个配置文件,它具有以下格式

variableName = value
variableName = value
variableName = value

I know I can read file split them store them in variable. But I am looking for an easy way. For example I want to store variable names and its value in a file and I want when I read file it automatically restore variables and its values. ( I know how to do it in php and it is very easy but I am not java expert :( )

我知道我可以读取文件拆分它们将它们存储在变量中。但我正在寻找一种简单的方法。例如,我想将变量名称及其值存储在文件中,并且我希望在读取文件时它会自动恢复变量及其值。(我知道如何在 php 中做到这一点,这很容易,但我不是 Java 专家:()

My second question is about following file read. I have a file that has rows and colums it can be CSV, for example

我的第二个问题是关于以下文件读取。我有一个包含行和列的文件,它可以是 CSV,例如

one,two,three
four,five,six
seven,eight,nine

I want to read it that it return whole column for example ( one four seven ) same for others. I don't want to use OpenCSV as its not csv oriented application just for one function.

我想读到它返回整列,例如(一四七)对其他人相同。我不想将 OpenCSV 用作它的非面向 csv 的应用程序,仅用于一个功能。

EDITED:

编辑:



Is it possible to write all variable name and its value and when I read file it automatically declare those variable and assign values?

是否可以写入所有变量名及其值,并且当我读取文件时它会自动声明这些变量并赋值?

回答by Tim Bender

Use java.util.Propertiesto read in the key=valuefile. Here is a Sun tutorial.

使用java.util.Properties中读取key=value文件。这是 Sun 教程

As for the CSV, you can read in all the lines and use String#split()to break each line into an array of values.

至于 CSV,您可以读入所有行并用于String#split()将每一行分成一组值。

回答by marklai

The Propertiesclass will load your config file in the name=value format. Call the load method with a FileReaderto the config file. The you can access any variable using the getProperty method.

属性类将在name = value的格式加载您的配置文件。使用FileReader调用 load 方法到配置文件。您可以使用 getProperty 方法访问任何变量。

Properties props = new Properties();
props.load(new FileReader(configFilePath));

String value = props.getProperty("name");

As for the CSV file, if all rows have the same number of values, you can read each line into an array using String.split(",") and assign it to a 2-d array. Then access a "column" by walking the 2-d array.

对于 CSV 文件,如果所有行具有相同数量的值,则可以使用 String.split(",") 将每一行读入数组并将其分配给二维数组。然后通过遍历二维数组来访问“列”。

回答by Micha? Ziober

  • 1 question: check Serialization
  • 2 question: Please see this source code:

    class RowReader {
    private String path;
    private String columnSeparator;
    private List<String[]> rows;
    private int columnCount;
    public RowReader(String path, String columnSeparator) {
        this.path = path;
        this.columnSeparator = columnSeparator;
        this.rows = getRows();
        if (this.rows == null || this.rows.size() == 0)
            this.columnCount = 0;
        else
            this.columnCount = this.rows.get(0).length;
    }
    
    public List<String> getColumn(int i) {
        List<String> column = new ArrayList<String>();
        for (String[] row : rows) {
            column.add(row[i]);
        }
        return column;
    }
    
    public int getColumnCount() {
        return columnCount;
    }
    
    private List<String[]> getRows() {
        List<String[]> rows = new ArrayList<String[]>();
        try {
            FileInputStream fstream = new FileInputStream(path);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line = null;
            while ((line = br.readLine()) != null) {
                rows.add(line.split(columnSeparator));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rows;
    }}
    
  • 1个问题:检查序列化
  • 2 问题:请参阅此源代码:

    class RowReader {
    private String path;
    private String columnSeparator;
    private List<String[]> rows;
    private int columnCount;
    public RowReader(String path, String columnSeparator) {
        this.path = path;
        this.columnSeparator = columnSeparator;
        this.rows = getRows();
        if (this.rows == null || this.rows.size() == 0)
            this.columnCount = 0;
        else
            this.columnCount = this.rows.get(0).length;
    }
    
    public List<String> getColumn(int i) {
        List<String> column = new ArrayList<String>();
        for (String[] row : rows) {
            column.add(row[i]);
        }
        return column;
    }
    
    public int getColumnCount() {
        return columnCount;
    }
    
    private List<String[]> getRows() {
        List<String[]> rows = new ArrayList<String[]>();
        try {
            FileInputStream fstream = new FileInputStream(path);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line = null;
            while ((line = br.readLine()) != null) {
                rows.add(line.split(columnSeparator));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rows;
    }}
    

Test class:

测试类:

public class Program {
    public static void main(String[] args) {
        RowReader reader = new RowReader("j:\test.txt", ",");
        for (int i = 0; i < reader.getColumnCount(); i++) {
            List<String> column = reader.getColumn(i);
            for (String c : column)
                System.out.print(c + ", ");
            System.out.println();
        }
    } 
}

Console output:

控制台输出:

one, four, seven, 
two, five, eight, 
three, six, nine, 

回答by WarmWaffles

Try reading in everything and using a regular expression splitting the list in to a 2-d array.

尝试阅读所有内容并使用正则表达式将列表拆分为二维数组。