Basic operations such as reading and writing txt, Excel, csv, and a brief introduction to third-party toolkit methods. (java)

Notes, a complete collection of tools for operating files, all code function directories are marked, if you need to find the directory; this article is continuously updated!

IO

JDK native

Txt

Get Txt content (read string by line)

  /**
    txtPath: 文件路径
    return : 行内容列表
  */
    public static List<String> getTxt(String txtPath){
    
    

        File file = new File(txtPath);
        BufferedReader reader = null;
        String temp = null;
        List<String> resList = new ArrayList<>();
        try {
    
    
            reader = new BufferedReader(new FileReader(file));
            while ((temp = reader.readLine()) != null) {
    
    
                System.out.println(temp);
                resList.add(temp);
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            if (reader != null) {
    
    
                try {
    
    
                    reader.close();
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
            }
        }
        return resList;
    }

Excel

     //maven
        <!-- poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>


Create Excel write content

    //生成文件位置
    private static final String PATH="D:\\3\\";

    public static void testWrite() throws Exception {
    
    

        Workbook workbook = new HSSFWorkbook();
        //创建一个工作表sheet
        Sheet sheet = workbook.createSheet("第一个sheet");
        //创建一行(0表示创建的是第一行)
        Row row1 = sheet.createRow(0);
        //创建一个单元格(这个单元格表示的是第一行第一列的单元格,即坐标(1,1))
        Cell cell11 = row1.createCell(0);
        //赋值
        cell11.setCellValue("坐标(1,1)");
        //在创建一个  坐标  1,2
        Cell cell = row1.createCell(1);
        cell.setCellValue("坐标 1,2");
        //生成Excel文件(使用io流),注:文件后缀要与excel版本对应
        FileOutputStream fileOutputStream = new FileOutputStream(PATH + "test.xls");
        //写入
        workbook.write(fileOutputStream);
        //文件写完后关闭流
        fileOutputStream.close();
    }

Read Excel content


    /**
     * 读取Excel 某列数据
     * @param filePath excel文件路径
     * @param cellNum 获取的列数  1开始
     * @return
     */
    public static List<String> readExcel(String filePath,int cellNum) {
    
    
        List<String> resList =new ArrayList<>();
        String path = filePath;
        Workbook workbook = ExcelUtil.getWorkbook(path);
        Sheet sheetAt = workbook.getSheetAt(cellNum-1);
        //获取最大行数
        int rowNum = sheetAt.getPhysicalNumberOfRows();
        for (int i = 1; i < rowNum; i++) {
    
    
            Row row1 = sheetAt.getRow(i);
            String s1 = row1.getCell(0).toString();
            resList.add(s1);
        }

        return  resList;
    }

    //获取读取excel对象
    public static Workbook getWorkbook(String filePath) {
    
    
        Workbook wb = null;
        if (filePath == null) {
    
    
            return null;
        }
        String extString = filePath.substring(filePath.indexOf('.'));
        InputStream is = null;
        try {
    
    
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
    
    
                return wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
    
    
                return wb = new XSSFWorkbook(is);
            } else {
    
    
                return wb = null;
            }

        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        return wb;
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
    
    
        List<String> list = ExcelUtil.readExcel("D:\\3\\其它\\military.xlsx", 1);
        for (String s : list) {
    
    
            System.out.println(s);
        }


    }



Modify Excel content

    public static void main(String[] args) {
    
    
        Workbook workbook = getWorkbook("D:/3/其它/military.xlsx");
        Sheet sheetAt = workbook.getSheetAt(0);
        //System.out.println(sheetAt);
        Row row = sheetAt.getRow(1);
        //System.out.println(row);
        Cell cell = row.getCell(2);
        System.out.println(cell);
        cell.setCellValue("中中");
        try {
    
    
            FileOutputStream fos = new FileOutputStream("D:/3/其它/military.xlsx");
            workbook.write(fos);

        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }

Excel to csv

    <dependencies>
		<dependency>
            <groupId>e-iceblue</groupId>
            <artifactId>spire.xls</artifactId>
            <version>12.11.8</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
            <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
    </repositories>
    
          
        // excel 转csv
    public static void excelToCsv(String excelPath,String csvPath){
    
    
        //创建Workbook类的对象
        com.spire.xls.Workbook workbook = new com.spire.xls.Workbook();
        //加载Excel
        workbook.loadFromFile(excelPath);

        //获取第一张工作表sheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //保存为CSV
        sheet.saveToFile(csvPath, ",", Charset.forName("UTF-8"));
    }

commons-io toolkit

// maven
            <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.11.0</version>
            </dependency>

read txt text

    private static String txtPath = "D:\\3\\test.txt";

    public static void main(String[] args) throws IOException {
    
    
        File file = new File(txtPath);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        System.out.println(new String(bytes));
	}

hutooltoolkit

// maven
		<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-core</artifactId>
            <version>5.7.20</version>
        </dependency>

Read local file to get byte stream

        // 本地文件路径
        String filePath = "D:\\3\\后台开发项目\\entity.json";
        File file = new File(filePath);
        byte[] bytes = FileUtil.readBytes(file);


Guess you like

Origin blog.csdn.net/pgcdnameming/article/details/128827944