美文网首页
java 读写文件

java 读写文件

作者: 谢贤byte | 来源:发表于2020-10-09 18:53 被阅读0次

    用Apache POI读excel(.xlsx)文件

    //新建输入字节流
    FileInputStream input = new FileInputStream(file);
    //获取XSSFWorkbook对象,代表工作簿
    XSSFWorkbook book = new XSSFWorkbook(input);
    //获取XSSFSheet对象,代表第一张工作表
    XSSFSheet sheet = book.getSheetAt(0);
    //遍历工作表的所有存在记录的行
    Iterator<Row> rowIt = sheet.cellIterator();
    Row row;
    Cell cell;
    //表示整个工作簿的内容
    List<Object> content = new ArrayList<Object>();
    //表示工作表的一行的记录
    List<String> entry;
    while(rowIt.hasNext()) {
        row = rowIt.next();
        Iterator<Cell> cellIt = row.iterator();
        entry = new ArrayList<String>();
        while(cellIt.hasNext()) {
            cell =  cellIt.next();
            //判断单元格类型
            switch(cell.getCellType()) {
                case STRING:
                    entry.add(cell.getStringCellValue());
                    break;
                case BLANK:
                    break;
                default:
                    break;
            }
        }
        content.add(entry);
    }
    

    用Apache POI写excel(.xlsx)文件

    //创建工作簿
    XSSFWorkbook book = new XSSFWorkbook();
    //新增工作表
    XSSFSheet sheet = book.createSheet();
    XSSFRow row;
    XSSFCell cell;
    
    //entry collection
    Map<Integer, Object[]> entries = new HashMap<Integer, Object[]>();
    entries.put(0, new Object[]{"name", "sex"});
    entries.put(1, new Object[]{"xzj", "male"});
    entries.put(2, new Object[]{"luise", "female"});
    
    Set<Integer> rownumSet = entries.keySet();
    for(int rownum : rownumSet) {
        //新增一行
        row = sheet.createRow(rownum);
        Object[] entry = entries.get(rownum);
        int index = 0;
        for(Object param : entry) {
            //新增单元格
            cell = row.createCell(index++);
            //设置单元格的值
            cell.setCellValue(param.toString());
        }
    }
    
    FileOutputStream output = new FileOutputStream(file);
    //把工作簿写入到字节流
    book.write(output);
    

    使用JAXP(Java API for XML Processing)读写XML文档,支持两种解析方式:DOM和SAX(Simple API for XML)。用DOM解析XML文档,需要读取整个文档。用SAX解析XML文档,一边读取文档一边解析。

    解析DOM读XML文档

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //创建DocumentBuilder对象
    DocumentBuilder builder = factory.newDocumentBuilder();
    //解析文件
    Document doc = builder.parse(new File("/dir"));
    //根据标签名称获取根节点
    NodeList nodeList = doc.getElementsByTagName("tag_name");
    //保存节点数据
    List<String> content = new ArrayList<String>();
    //子节点列表
    NodeList subNodeList;
    //子节点
    Node subNode;
    for(int i=0; i<nodeList.getLength(); i++) {
        //获取子节点
        subNodeList = nodeList.item(i).getChildNodes();
        for (int j=0; j<subNodeList.getLength(); j++) {
            //获取子节点的子节点
            subNode = subNodeList.item(j);
            //判断节点类型
            if(subNode.getNodeType() == Node.ELEMENT_NODE) {
                content.add(subNode.getTextContent());
            }
        }
    }
    

    构造DOM写XML文档

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //创建DocumentBuilder对象
    DocumentBuilder builder = factory.newDocumentBuilder();
    //创建Document对象
    Document doc = builder.newDocument();
    //设置xml文档version
    doc.setXmlVersion("1.0");
    doc.setXmlStandalone(true);
    //创建根节点
    Element root = doc.createElement("info");
    //创建person子节点
    Element person = doc.createElement("person");
    //创建name子节点
    Element name = doc.createElement("name");
    name.setTextContent("xzj");
    //把name子节点添加到person节点
    person.appendChild(name);
    //创建sex子节点
    Element sex = doc.createElement("sex");
    sex.setTextContent("male");
    //把sex子节点添加到person节点
    person.appendChild(sex);
    //把person节点添加到根节点
    root.appendChild(person);
    //把根节点添加到xml文档
    doc.appendChild(root);
    TransformerFactory transFormers = TransformerFactory.newInstance();
    Transformer transFormer = transFormers.newTransformer();
    //设置缩进
    transFormer.setOutputProperty(OutputKeys.INDENT, "yes");
    //把Document对象所代表的xml文档写入xml文件
    transFormer.transform(new DOMSource(doc), new StreamResult(new File("/dir")));
    

    用dom4j读XML文档

    SAXReader reader = new SAXReader();
    //读取文件
    Document doc = reader.read(new File("/dir"));
    //获取根节点
    Element root = doc.getRootElement();
    //获取根节点包含的子节点
    List<Element> elements = root.elements();
    //保存所有节点的数据
    List<Object> content = new ArrayList<Object>();
    //保存一个节点的数据
    List<String> tag = new ArrayList<String>();
    for(Element e : elements) {
        //根据标签名称获取标签内容
        tag.add(e.element("tag_name").getText());
        content.add(tag);
        tag = new ArrayList<String>();
    }
    

    用dom4j写XML文档

    //新建Document对象
    Document doc = DocumentHelper.createDocument();
    //增加根节点
    Element root = doc.addElement("info");
    //增加person子节点
    Element person = root.addElement("person");
    //增加name子节点
    Element name = person.addElement("name").addText("xzj");
    //增加sex子节点
    Element sex = person.addElement("sex").addText("male");
    FileWriter out = new FileWriter("/dir");
    XMLWriter writer = new XMLWriter(out);
    writer.write(doc);
    writer.close();
    

    从数据库中读取图片

    public static final int LENGTH = 20000;
    String fileName = "image";
    String path = "E:\\images\\";
    byte[] b = new byte[LENGTH];
    File file = null;
    int total;      
    while(resultSet.next()){
        fileName = rs.getString("bid");
        InputStream input = rs.getBinaryStream("filebody");
        if(input == null) {
            continue;
        }
        input.read(b);
        file = new File(path+fileName+".jpg");
        OutputStream output = new FileOutputStream(file);
        output.write(b);
        System.out.printf("图片有%dbyte\n", total);
    }
    

    读取properties文件

    1. 使用java.util.ResourceBundle
    2. 使用java.util.Properties
      路径:src/main/resources/demo.properties
      代码:
    Properties properties = new Properties();
    InputStream stream = this.getClass().getResourceAsStream("/demo.properties");
    properties.load(stream);
    String value = properties.getProperty("key");
    Map<String, String> hashMap = new HashMap<String, String>();
    hashMap.put("key", value);
    

    相关文章

      网友评论

          本文标题:java 读写文件

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