美文网首页
外部数据处理之Java

外部数据处理之Java

作者: halfempty | 来源:发表于2018-12-20 13:04 被阅读0次

1 txt

Java7新引入了Path, 用于取代File

Files提供了文件的基本操作, 包括基本属性, 输入输出流

Path path = Paths.get(basePath, "data.txt");

Files.lines(path, StandardCharsets.UTF_8).forEachOrdered(p -> {
    // do some action
});

2 xml

使用Dom4j

按DOM方式解析XML文件, 分成三种节点: Element, Attribue, Text

SAXReader reader = new SAXReader();
Document document = reader.read(path.toFile());

Element books = document.getRootElement();
Iterator<Element> bookIter = books.elementIterator("book");
while(bookIter.hasNext()) {
    Element book = bookIter.next();
    System.out.println(book.attributeCount());
    System.out.println(book.attributeValue("type"));

    Iterator<Element> fields = book.elementIterator();
    while(fields.hasNext()) {
        Element field = fields.next();
        System.out.println(field.getQualifiedName());
        System.out.println(field.getTextTrim());
    }
}

3 json

使用fastjson解析

Path path = Paths.get(basePath, "data.json");
JSONObject json = JSON.parseObject(new String(Files.readAllBytes(path)));

json.getJSONObject("foods").getString("pork");

4 yml

使用snakeyaml

提前定义好javabean, loadAs可以直接加载数据生成对象

Yaml yaml = new Yaml();
Map<String, Object> content = yaml.loadAs(Files.newInputStream(path), Map.class);

5 excel

HSSFWorkbook -> xls

XSSFWorkbook -> xlsx

如果2种都有可能用到, 最好封装一个通过的方法

Workbook workbook = new XSSFWorkbook(Files.newInputStream(path));
System.out.println("Sheet nums: " + workbook.getNumberOfSheets());

Sheet sheet = workbook.getSheetAt(0);
System.out.println("Row num: " + sheet.getLastRowNum());

for(int i=0; i<sheet.getLastRowNum(); i++) {
    Row row = sheet.getRow(i);
    System.out.println("Col num: " + row.getLastCellNum());

    for(int j=0; j<row.getLastCellNum(); j++) {
        Cell cell = row.getCell(j);
        System.out.println(getCellValue(cell));
    }
}

static Object getCellValue(Cell cell) {
    Object value = null;

    CellType type = cell.getCellTypeEnum();
    if(type == CellType.STRING) {
        value = cell.getStringCellValue();
    } else if(type == CellType.NUMERIC) {
        value = cell.getNumericCellValue();
    } else if(type == CellType.BOOLEAN) {
        value = cell.getBooleanCellValue();
    }
    return value;
}

相关文章

网友评论

      本文标题:外部数据处理之Java

      本文链接:https://www.haomeiwen.com/subject/xhlykqtx.html