java读取文件工具类


参考链接:
(1) JAVA怎么读取.csv文件以及只读取.csv文件的某行某列的值
https://blog.csdn.net/qq_37591637/article/details/86487481

java不重启服务动态加载properties文件

java不重启服务动态加载properties文件

Maven依赖

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17-beta1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17-beta1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.17-beta1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans -->
        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans</artifactId>
            <version>2.6.0</version>
        </dependency>

ExcelUtils

package excel;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtils {

    public static void main(String[] args) {
        String filePath="";
        int stand=0;
        int index=1;

        // 字段 -> datasource
        Map<String,String> field2DataSource=readColumnWithField(filePath,stand,index);

        int index2=2;

        // 字段 -> IsArpeUpdate
        Map<String,String> field2Update=readColumnWithField(filePath,stand,index2);
    }


    /**
     * @param filePath Excel文件路径
     * @param stand
     * @param index 第index列(从0开始)
     * @return
     */
    public static Map<String,String> readColumnWithField(String filePath, int stand, int index) {
        Map<String,String> result=new HashMap<>();
        Workbook wb =null;
        Sheet sheet = null;
        Row row = null;
        String cellColnumField = null;
        String cellColnumData = null;
        //读取Excel文件
        wb = readExcel(filePath);
        //如果文件不为空
        if(wb != null){
            //获取第一个sheet
            sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            int colnum = row.getPhysicalNumberOfCells();
            //循环行
            for (int i = 1; i<rownum; i++) {
                row = sheet.getRow(i);
                if(row !=null){
                    // 获取指定列
                    // 第一列field 唯一
                    cellColnumField = (String) getCellFormatValue(row.getCell(stand));
                    // 对应的关联值
                    cellColnumData = (String) getCellFormatValue(row.getCell(index));
                    result.put(cellColnumField,cellColnumData);
                }else{
                    break;
                }
            }
        }
        return result;
    }


    //读取excel
    @SuppressWarnings("resource")
    public static Workbook readExcel(String filePath){
        Workbook wb = null;
        if(filePath==null){
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));//文件后缀名
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            //如果文件后缀名为xls
            if(".xls".equals(extString)){
                return wb = new HSSFWorkbook(is);
            }//如果文件后缀名为xlsx
            else if(".xlsx".equals(extString)){
                return wb = new XSSFWorkbook(is);
            }else{
                return wb = null;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }
    @SuppressWarnings("deprecation")
    public static Object getCellFormatValue(Cell cell){
        Object cellValue = null;
        if(cell!=null){
            //判断cell类型
            switch(cell.getCellType()){
                case Cell.CELL_TYPE_NUMERIC:{
                    cellValue = String.valueOf(cell.getNumericCellValue());
                    break;
                }
                case Cell.CELL_TYPE_FORMULA:{
                    //判断cell是否为日期格式
                    if(DateUtil.isCellDateFormatted(cell)){
                        //转换为日期格式YYYY-mm-dd
                        cellValue = cell.getDateCellValue();
                    }else{
                        //数字
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:{
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = "";
            }
        }else{
            cellValue = "";
        }
        return cellValue;
    }
}

CSVUtils

package excel;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;

public class CSVUtils {

    public static void main(String[] args) {
        String filePath="";
        String colName="";
        Map<String,String> field2DataSourceCSV =getAllColsByName(filePath, colName);

        String colName2="";
        Map<String,String> field2UpdateCSV =getAllColsByName(filePath, colName2);
    }

    /**
     * 获取所有行的指定列
     */
    public static Map<String,String> getAllColsByName(String filePath, String colName){
        Map<String,String> result=new HashMap<>();
        try {
            BufferedReader reade = new BufferedReader(new FileReader(filePath));//换成你的文件名
            String line = null;
            int index=0;
            while((line=reade.readLine())!=null){
                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分
                if(index>=1){
                    // 第一行是定义, 不需要
                    result.put(item[0],item[getColNumByColName(filePath,1,colName)]);
                }
                index++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取列Num
     * @param filePath
     * @param row
     * @param colName
     * @return
     */
    public static int getColNumByColName(String filePath, int row, String colName){
        try {
            BufferedReader reade = new BufferedReader(new FileReader(filePath));//换成你的文件名
            String line = null;
            int index=0;
            while((line=reade.readLine())!=null){
                String items[] = line.split(",");//CSV格式文件为逗号分隔符文件,这里根据逗号切分
                if(index==row-1){
                    for(int i=0;i<items.length;i++){
                        if(items[i].equals(colName)){
                            return i+1;
                        }
                    }
                }
                //int value = Integer.parseInt(last);//如果是数值,可以转化为数值
                index++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; import java.io.*; /** * FileUtil. Simple file operation class. * * @author BeanSoft * */ public class FileUtil { /** * The buffer. */ protected static byte buf[] = new byte[1024]; /** * Read content from local file. FIXME How to judge UTF-8 and GBK, the * correct code should be: FileReader fr = new FileReader(new * InputStreamReader(fileName, "ENCODING")); Might let the user select the * encoding would be a better idea. While reading UTF-8 files, the content * is bad when saved out. * * @param fileName - * local file name to read * @return * @throws Exception */ public static String readFileAsString(String fileName) throws Exception { String content = new String(readFileBinary(fileName)); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(String fileName, String encoding) throws Exception { String content = new String(readFileBinary(fileName), encoding); return content; } /** * 读取文件并返回为给定字符集的字符串. * @param fileName * @param encoding * @return * @throws Exception */ public static String readFileAsString(InputStream in) throws Exception { String content = new String(readFileBinary(in)); return content; } /** * Read content from local file to binary byte array. * * @param fileName - * local file name to read * @return * @throws Exception */ public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制字节数组. * @param streamIn * @return * @throws IOException */ public static byte[] readFileBinary(InputStream streamIn) throws IOException { BufferedInputStream in = new BufferedInputStream(streamIn); ByteArrayOutputStream out = new ByteArrayOutputStream(10240); int len; while ((len

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值