如何使用一些自定义配置设置属性文件

时间:2019-05-23 02:49:43

标签: java properties-file

我有一个代码可以使用Apache POI从excel文件中读取值,该excel文件的内容是一个具有多列和多行的大表,并且有许多具有相同结构(列数)的excel文件,有时可能具有不同的列名和不同的列值。

我的要求之一是将所有数据提取为两种不同的数据类型,一种是数值数据,它是Float类型,另一种是文本值,作为String。

问题1:如何将此逻辑传递到属性文件中,这样每当我需要解析一个excel文件时,它就可以为每列获取具有正确数据类型集的外部文件?

问题2:在下面的方法中,我将列位置设置为标识位置的键,但我认为将列名作为键值比使用数值更好,而不是使用数值,这样会更快读取属性文件并根据列名称设置数据类型值。

当前,我使用逻辑波纹管来固定列位置,其数据类型为String或Float,并且对于一个特定的excel文件也可以使用。

     String filePath;
     String fileProcessingType;

     Map<Integer, List<MergeCellRange>> mergeCellMap = new HashMap<>();
     Map<Integer, String> columnHeaderMap = new HashMap<>(););

     static NavigableMap<Integer, String> columnTypeMap = null; // map is used to identify the column
     // types of each parameter
    static {
      columnTypeMap = new TreeMap<Integer, String>();
      columnTypeMap.put(0, "String");
      columnTypeMap.put(1, "String"); // 1 TimeStamp as String
      columnTypeMap.put(2, "String"); // 2-66 String
      columnTypeMap.put(66, "String"); // 66 String
      columnTypeMap.put(67, "Float"); // 67-88 String
      columnTypeMap.put(89, "String"); // 89-90 String
      columnTypeMap.put(113, "String"); // 114....
    }

所以我的想法是拥有一个属性文件,例如:

 Column0=String
 Column1=String
 Column2=Float
 Column3=String
 Column4=Float
 Column5=Float
 Column6=String
 ...

然后选择它来调用属性文件:

FileInputStream newFile =新的FileInputStream(“ dataType.properties”);

Properties mappingFile = new Properties();
mappingFile.load(newFile);

mappingFile.load(newFile);

List = mappingFile.getProperties().list(System.out);

static NavigableMap<List> columnTypeMap = null; 
// map is used to identify the column

3 个答案:

答案 0 :(得分:1)

try(FileInputStream newFile=new FileInputStream("dataType.properties")) {
  Properties mappingFile =new Properties();
  mappingFile.load(newFile);
  mappingFile.forEach((c,t)-> {
    columnTypeMap.put(Integer.parseInt(((String)c).substring("Column".length())),(String)t);
  });
}
catch(Exception ex) {
  System.error.println(ex);
}

PS:您只需将属性写为

00=String
01=Float
02=...

并将映射部分简化为

    columnTypeMap.put(Integer.parseInt((String)c),(String)t);

答案 1 :(得分:0)

看看 Apache PropertiesConfiguration。 它仍然为您解决了基础知识:打开并解析属性文件,并通过键提供其内容。示例可以在文档中找到。

答案 2 :(得分:0)

首先,您可以检查POI's documentation on getting the data type of a cell

如果这对您不起作用,建议您查看Java Properties class。您可以在文件by keyby (key,value)中获得所有可用属性的列表。知道所需的数据类型后,即可直接处理单元格:as stringas a double

相关问题