文本工具

1. 创建文件路径

public void createFile1(String path) throws IOException {
File file = new File(path);
File fileParent = file.getParentFile();

//判断是否存在
if (!fileParent.exists()) {
fileParent.mkdirs();
}
file.createNewFile();
System.out.println(“创建成功”);
}
public Properties readerProperties(String file){
// /removeRepeat.properties
InputStream in = this.getClass().getResourceAsStream(file);
Properties props = new Properties();
InputStreamReader inputStreamReader = null;
try {
inputStreamReader = new InputStreamReader(in, “UTF-8”);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
props.load(inputStreamReader);
} catch (IOException e) {
e.printStackTrace();
}
return props;
}

2. 读写

public void duXie(String path,boolean flag) throws IOException {
    //读txt
    File filename = new File(path);
    InputStreamReader reader = new InputStreamReader(
            new FileInputStream(filename));
    BufferedReader br = new BufferedReader(reader);
    String line;
    while ((line = br.readLine())!= null) {
        BasicDBObject cond1 = new BasicDBObject();
        cond1.append("_id", new ObjectId(line));
    }
    //写txt
    FileWriter fw = new FileWriter(path,flag);
    BufferedWriter bw = new BufferedWriter(fw);

    //读csv
    String filePath = "E:\\Test\\成都市场主体_第二份.csv";
    CsvReader reader1 = new CsvReader(filePath, ',', Charset.forName("utf-8"));
    reader1.readHeaders(); // 跳过表头, 如果不需要表头的话,不要写这句。
    while (reader1.readRecord()){
        reader1.get(0);
        reader1.get("beginDate");
    }

    //写CSV
    String src = "E:\\HA\\bb\\深圳上市股票名单2(需补齐企业名称)0181208.csv";
    CsvWriter csvWriter = new CsvWriter(src, ',', Charset.forName("UTF-8"));
    //设置列头
    String[] csvHeaders = {"上市企业简称","企业名全称","股票类型"};
    csvWriter.writeRecord(csvHeaders);

    String[] csvContent={"","", ""};
    csvWriter.writeRecord(csvContent);

    csvWriter.close();
}

3. 中文符号转英文符号形式

public static String ToSBC(String input) {
    char[] c = input.toCharArray();
    for (int i = 0; i < c.length; i++) {
        if (c[i] == 12288) {
            c[i] = (char) 32;
            continue;
        }
        if (c[i] > 65280 && c[i] < 65375)
            c[i] = (char) (c[i] - 65248);
    }
    return new String(c);
}
  1. 读.xls或.xlsx
package Utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class ReadExcelUtils {
    private Logger logger = LoggerFactory.getLogger(ReadExcelUtils.class);
    private Workbook wb;
    private Sheet sheet;
    private Row row;

    public ReadExcelUtils(String filepath) {
        if(filepath==null){
            return;
        }
        String ext = filepath.substring(filepath.lastIndexOf("."));
        try {
            InputStream is = new FileInputStream(filepath);
            if(".xls".equals(ext)){
                wb = new HSSFWorkbook(is);
            }else if(".xlsx".equals(ext)){
                wb = new XSSFWorkbook(is);
            }else{
                wb=null;
            }
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException", e);
        } catch (IOException e) {
            logger.error("IOException", e);
        }
    }

    /**
     * 读取Excel表格表头的内容
     *
     * @param //InputStream
     * @return String 表头内容的数组
     * @author zengwendong
     */
    public String[] readExcelTitle() throws Exception{
        if(wb==null){
            throw new Exception("Workbook对象为空!");
        }
        sheet = wb.getSheetAt(0);
        row = sheet.getRow(0);
        // 标题总列数
        int colNum = row.getPhysicalNumberOfCells();
        System.out.println("colNum:" + colNum);
        String[] title = new String[colNum];
        for (int i = 0; i < colNum; i++) {
            // title[i] = getStringCellValue(row.getCell((short) i));
            title[i] = row.getCell(i).getCellFormula();
        }
        return title;
    }

    /**
     * 读取Excel数据内容
     *
     * @param// InputStream
     * @return Map 包含单元格数据内容的Map对象
     * @author zengwendong
     */
    public Map<Integer, Map<Integer,Object>> readExcelContent() throws Exception{
        if(wb==null){
            throw new Exception("Workbook对象为空!");
        }
        Map<Integer, Map<Integer,Object>> content = new HashMap<Integer, Map<Integer,Object>>();

        sheet = wb.getSheetAt(0);
        // 得到总行数
        int rowNum = sheet.getLastRowNum();
        row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells();
        // 正文内容应该从第二行开始,第一行为表头的标题
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            int j = 0;
            Map<Integer,Object> cellValue = new HashMap<Integer, Object>();
            while (j < colNum) {
                Object obj = getCellFormatValue(row.getCell(j));
                cellValue.put(j, obj);
                j++;
            }
            content.put(i, cellValue);
        }
        return content;
    }

    /**
     *
     * 根据Cell类型设置数据
     *
     * @param cell
     * @return
     * @author zengwendong
     */
    private Object getCellFormatValue(Cell cell) {
        Object cellvalue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC:// 如果当前Cell的Type为NUMERIC
                case Cell.CELL_TYPE_FORMULA: {
                    // 判断当前的cell是否为Date
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date类型则,转化为Data格式
                        // data格式是带时分秒的:2013-7-10 0:00:00
                        // cellvalue = cell.getDateCellValue().toLocaleString();
                        // data格式是不带带时分秒的:2013-7-10
                        Date date = cell.getDateCellValue();
                        cellvalue = date;
                    } else {// 如果是纯数字

                        // 取得当前Cell的数值
                        cellvalue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:// 默认的Cell值
                    cellvalue = "";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }
    public static void main(String[] args) {
        try {
            String filepath = "F:\\test\\信息数据需求.xlsx";
            ReadExcelUtils excelReader = new ReadExcelUtils(filepath);
           //  对读取Excel表格标题测试
			/*String[] title = excelReader.readExcelTitle();
			System.out.println("获得Excel表格的标题:");
			for (String s : title) {
				System.out.print(s + " ");
			}*/

            // 对读取Excel表格内容测试
            Map<Integer, Map<Integer,Object>> map = excelReader.readExcelContent();
            System.out.println("获得Excel表格的内容:");
            for (int i = 1; i <= map.size(); i++) {
                System.out.println(map.get(i).get(0)+" "+map.get(i).get(1));
            }
        } catch (FileNotFoundException e) {
            System.out.println("未找到指定路径的文件!");
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }



}

    在这里插入代码片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值