一、文件复制

package file;import org.apache.commons.io.FileUtils;import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;/*** @Author:张金贺* @Date:2022/7/23 13:29* @Version 1.0*/
public class finder {public static void main(String[] args) {
//        File file =new File();
//        file.isDirectory();
//        File[] files = file.listFiles();
//        file.getAbsolutePath();finder finder=new finder();String fileType= args[0];String sourcePath= args[1];String desPath= args[2];finder.copyAllFileToDestDir(fileType,sourcePath,desPath);}public void copyAllFileToDestDir(String fileType,String sourcePath,String desPath){
//        搜索指定类型文件List<File> fileList= searchFiles(fileType,sourcePath);
//       复制文件copyFiles(fileList,desPath);}/***   搜索指定类型的文件* @param fileType   文件类型* @param sourcePath  源路径* @return*/private List<File> searchFiles(String fileType, String sourcePath) {
//        返回结果集List<File> fileList=new ArrayList<>();
//        源文件夹对象File file=new File(sourcePath);if (file.isDirectory()){
//            加载文件夹中的文件loadFiles(fileType,file,fileList);}return fileList;}/***   加载file对象中的所有指定类型的文件,并放入fileList中* @param fileType   文件类型* @param file   源文件夹* @param fileList   返回结果集*/private void loadFiles(String fileType, File file, List<File> fileList) {File[] files = file.listFiles();if (files==null||files.length<=0){return;}for (File f : files) {if (f.isFile()&&f.getName().endsWith(fileType)){fileList.add(f);}else if (f.isFile()&& !f.getName().endsWith(fileType)){continue;}else {loadFiles(fileType,f,fileList);}}}/**** @param fileList  需要复制的文件夹列表* @param desPath  复制到哪个目录*/private void copyFiles(List<File> fileList, String desPath) {if (fileList==null ||fileList.isEmpty()){return;}File desFile =new File(desPath);for (File file : fileList) {try {FileUtils.copyFileToDirectory(file,desFile);} catch (IOException e) {e.printStackTrace();}}}
}

二、文件读写与图像处理

1.文档读

package file.manager;import java.io.*;/*** @Author:张金贺* @Date:2022/7/23 14:44* @Version 1.0*/
public class MyFileReader {public static void main(String[] args) {MyFileReader myFileReader =new MyFileReader();File file =new File("./test.txt");
//        myFileReader.readFileByLine(new File("./test.txt"));
//        myFileReader.readFileBySize(file,5);myFileReader.readTotalFile(file);}//按行读取文件public void readFileByLine(File file){try {BufferedReader bufferedReader =new BufferedReader(new FileReader(file)) ;String line =null;while ((line =bufferedReader.readLine())!=null){System.out.println(line);}
//            bufferedReader.readLine();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
//按指定长度读取文件public void readFileBySize(File file,int size){try {BufferedReader bufferedReader =new BufferedReader(new FileReader(file)) ;char[] chars =new char[size];while (-1!= bufferedReader.read(chars)){System.out.println(new String(chars));}bufferedReader.read(chars);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
//读取整个文件public void readTotalFile(File file){try (FileInputStream fileInputStream = new FileInputStream(file)) {byte[] bytes=new byte[(int) file.length()];//建议1024,防止文件过大带来的影响while (-1!=fileInputStream.read(bytes)){System.out.println(new String(bytes));}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}

2.文档写

package file.manager;import java.io.*;
import java.nio.charset.StandardCharsets;/*** @Author:张金贺* @Date:2022/7/23 15:05* @Version 1.0*/
public class MyFileWriter {//   文档写入:追加写入、清空写入public static void main(String[] args) {File file=new File("./test.txt");MyFileWriter myFileWriter=new MyFileWriter();myFileWriter.writeContentToFile(file,false);}public void writeContentToFile(File file,boolean isAppend){try {BufferedOutputStream bufferedOutputStream=new BufferedOutputStream(new FileOutputStream(file,isAppend));bufferedOutputStream.write("123".getBytes());} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}

3.图像处理---缩放图片

package net.csdn.image;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;/*** @Author:张金贺* @Date:2022/7/23 15:17* @Version 1.0*/
public class imageScale {public static void main(String[] args) throws IOException {imageScale imageScale=new imageScale();imageScale.scaleImage(new File("boy.png"),new File("boy1.png"),0.8);}/*** 缩放图片* @param sourceImageFile   源文件对象* @param destImageFile   目标文件对象* @param scale   缩放比例*/public void scaleImage(File sourceImageFile,File destImageFile,double scale) throws IOException {BufferedImage bufferedImage= ImageIO.read(sourceImageFile);int width = bufferedImage.getWidth();int height = bufferedImage.getHeight();Image scaledInstance = bufferedImage.getScaledInstance(Double.valueOf(width * scale).intValue(), Double.valueOf(height * scale).intValue(), Image.SCALE_DEFAULT);BufferedImage newImage=new BufferedImage(Double.valueOf(width * scale).intValue(), Double.valueOf(height * scale).intValue(),BufferedImage.TYPE_INT_ARGB);Graphics g = newImage.getGraphics();g.drawImage(scaledInstance,0,0,null);g.dispose();ImageIO.write(newImage,"png",destImageFile);}
}

4.图像处理---添加水印

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;/*** @Author:张金贺* @Date:2022/7/23 15:38* @Version 1.0*/
public class WaterMark {public static void main(String[] args) throws IOException {File file=new File("LOGO.png");WaterMark waterMark=new WaterMark();waterMark.addWaterMark(file);}/*** 加水印* @param file   需要加水印的图片对象*/public void addWaterMark(File file) throws IOException {//1读取图片文件BufferedImage bufferedImage = ImageIO.read(file);//2加水印Graphics g = bufferedImage.getGraphics();g.setColor(Color.BLUE);g.setFont(new Font("SimHei",Font.BOLD,50));g.drawString("hello word",100,200);//3输出加水印之后的图片ImageIO.write(bufferedImage,"png",new File("watermark.png"));}
}

5.图像处理---图片添加滤镜

package image;import com.jhlabs.image.InvertFilter;
import com.jhlabs.image.PointFilter;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;/*** @Author:张金贺* @Date:2022/7/23 16:07* @Version 1.0*/
//jar包地址:jhlabs.com/ip/filters/index.html
public class filterr {public static void main(String[] args) throws IOException {filterr filterr=new filterr();filterr.addImageFilter(new File("LOGO.png"),new File("filter.png"),new InvertFilter());}public void addImageFilter(File sourceImageFile, File destFile, PointFilter pointFilter) throws IOException {BufferedImage sourceImage = ImageIO.read(sourceImageFile);Image scaledInstance = sourceImage.getScaledInstance(sourceImage.getWidth(), sourceImage.getHeight(), Image.SCALE_DEFAULT);BufferedImage bufferedImage=new BufferedImage(sourceImage.getWidth(),sourceImage.getHeight(),BufferedImage.TYPE_INT_ARGB);Graphics graphics = bufferedImage.getGraphics();graphics.drawImage(scaledInstance,0,0,null);graphics.dispose();pointFilter.filter(sourceImage,bufferedImage);ImageIO.write(bufferedImage,"png",destFile);}
}

三、自动化电子表格处理

1.添加jar包

网盘文件CSDN文件夹内

2.使用步骤

(1)创建表格类文件

package csdn;/*** @Author:张金贺* @Date:2022/7/28 14:53* @Version 1.0*/
public class Person {private String name;private String city;private String cellPhone;public String getName() {return name;}public Person(String name, String city, String cellPhone) {this.name = name;this.city = city;this.cellPhone = cellPhone;}public void setName(String name) {this.name = name;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getCellPhone() {return cellPhone;}public void setCellPhone(String cellPhone) {this.cellPhone = cellPhone;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", city='" + city + '\'' +", cellPhone='" + cellPhone + '\'' +'}';}
}

(2)表格写入

package csdn;import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;/*** @Author:张金贺* @Date:2022/7/28 14:48* @Version 1.0*/
public class ExcelWriter {public static void main(String[] args) throws IOException {ExcelWriter excelWriter = new ExcelWriter();
//        excelWriter.fillExcel(null,new File("D:\\Person.xls"));List<Person> personList = new ArrayList<>();personList.add(new Person("张金贺","北京","13888888888"));excelWriter.fillExcel(personList,new File("D:\\Person.xls"));}/*** 写入Excel文件** @param data   用户数据* @param dataFile   目标文件*/public void fillExcel(List<Person> data, File dataFile) throws IOException {XSSFWorkbook xssWorkbook = new XSSFWorkbook();XSSFSheet sheet = xssWorkbook.createSheet("用户");XSSFRow row = sheet.createRow(0);row.createCell(0).setCellValue("姓名");row.createCell(1).setCellValue("城市");row.createCell(2).setCellValue("手机号");for (int i = 0; i < data.size(); i++) {XSSFRow r = sheet.createRow(i + 1);r.createCell(0).setCellValue(data.get(i).getName());r.createCell(1).setCellValue(data.get(i).getCity());r.createCell(2).setCellValue(data.get(i).getCellPhone());}FileOutputStream fileOutputStream = new FileOutputStream(dataFile);xssWorkbook.write(fileOutputStream);fileOutputStream.close();xssWorkbook.close();}
}

(3)表格读取

package csdn;import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;/*** @Author:张金贺* @Date:2022/7/28 15:18* @Version 1.0*/
public class ExcelReader {public static void main(String[] args) throws IOException {ExcelReader excelReader = new ExcelReader();excelReader.readExcel(new File("D:\\Person.xls"));}/*** 读取Excel文件* @param dataFile   源文件对象*/public void readExcel(File dataFile) throws IOException {XSSFWorkbook xssWorkbook = new XSSFWorkbook(new FileInputStream(dataFile));XSSFSheet sheet = xssWorkbook.getSheetAt(0);Iterator<Row> rowIterator = sheet.rowIterator();while (rowIterator.hasNext()) {org.apache.poi.ss.usermodel.Row row = rowIterator.next();System.out.println(row.getCell(0).getStringCellValue() + " " + row.getCell(1).getStringCellValue() + " " + row.getCell(2).getStringCellValue());}xssWorkbook.close();
//        for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
//            XSSRow row = sheet.getRow(i);
//            System.out.println(row.getCell(0).getStringCellValue() + " " + row.getCell(1).getStringCellValue() + " " + row.getCell(2).getStringCellValue());
//        }
//        xssWorkbook.close();}
}

3.案例

package csdn;import com.github.javafaker.Faker;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.Stream;/*** @Author:张金贺* @Date:2022/7/29 13:28* @Version 1.0*/
public class PoiDemo {public static void main(String[] args) throws IOException {//创建一个工作薄XSSFWorkbook xssfWorkbook = new XSSFWorkbook();//创建一个sheet,名字为personxssfWorkbook.createSheet("person");XSSFSheet sheet = xssfWorkbook.getSheet("person");//创建第一行,行的下标从0开始XSSFRow row = sheet.createRow(0);//设置第一行的第一列为姓名,也就是设置表头的内容row.createCell(0).setCellValue("姓名");//设置第一行的第二列为城市row.createCell(1).setCellValue("城市");//设置第一行的第三列为手机号row.createCell(2).setCellValue("手机号");Faker faker = new Faker(Locale.CHINA);//生成10个随机人物信息List<Person> personList = Stream.generate(() -> new Person(faker.name().fullName(), faker.address().city(), faker.phoneNumber().cellPhone())).limit(10).collect(Collectors.toList());//将人物数据写入表格for (int i = 0; i < personList.size() ; i++) {XSSFRow sheetRow = sheet.createRow(i+1);Person person = personList.get(i);sheetRow.createCell(0).setCellValue(person.getName());sheetRow.createCell(1).setCellValue(person.getCity());sheetRow.createCell(2).setCellValue(person.getCellPhone());}//创建一个文件,用于将表格内容输出到该文件中File file = new File("person.xlsx");xssfWorkbook.write(new FileOutputStream(file));}}

Java操作磁盘文件相关推荐

  1. java中删除sqlite数据库语句_sqlite数据库的介绍与java操作sqlite的实例讲解

    sqlite数据库的介绍与java操作sqlite的实例讲解 发布时间:2020-10-03 05:40:34 来源:脚本之家 阅读:92 作者:Lee_Tech sqlite是啥? 1.一种轻型数据 ...

  2. java 操作 redis_java操作Redis

    10. java操作Redis 10.1 环境准备 1. 引入依赖 redis.clients jedis 2.9.0 2.创建jedis对象 package org.example; import ...

  3. HBase安装配置以及Java操作hbase

    2019独角兽企业重金招聘Python工程师标准>>> Apache HBase Apache HBase™是Hadoop数据库,是一个分布式,可扩展的大数据存储. 当您需要对大数据 ...

  4. Java操作Kafka执行不成功

    使用kafka-clients操作kafka始终不成功,原因不清楚,下面贴出相关代码及配置,请懂得指点一下,谢谢! 环境及依赖 <dependency><groupId>org ...

  5. java操作elasticsearch实现query String

    1.CommonTersQuery: 指定字段进行模糊查询 //commonTermsQuery @Test public void test35() throws UnknownHostExcept ...

  6. java操作dom节点的添加_java操作DOM节点的添加,删除,修改

    java操作DOM节点的添加,删除,修改 下面我们开始对此xml添加,删除,修改:方法一 import java.io.File; import java.io.IOException; import ...

  7. rocketmq(三 java操作rocket API, rocketmq 幂等性)

    JAVA操作rocketmq: 1.导入rocketmq所需要的依赖: <dependency><groupId>com.alibaba.rocketmq</groupI ...

  8. redis入门及java操作

    redis 命令可以去菜鸟教程http://www.runoob.com/redis/redis-tutorial.html 或者以下地址去学习http://www.cnblogs.com/huang ...

  9. java excel读取操作,Java 操作 Excel (读取Excel2003 2007,Poi兑现)

    Java 操作 Excel (读取Excel2003 2007,Poi实现) 一. Apache POI 简介( http://poi.apache.org/) 使用Java程序读写Microsoft ...

最新文章

  1. 竟有内鬼!北理工硕士生「复制粘贴」论文,旷视研究员最新声明
  2. java环境变量设置
  3. CPU指令集是什么东西
  4. 【Linux】一步一步学Linux——lsattr命令(116)
  5. DWZ关闭navTab后刷新指定的navTab
  6. AGC001 补题小结
  7. mysql rsync复制,mysql复制又同步
  8. Android系统(76)---ART和Dalvik区别
  9. 最硬核Visual AssistX 安装破解(2019最新 通用)内含破解原理
  10. 如何提高VS2010的性能,VS2010不再…
  11. 中文情感分析——snownlp类库 源码注释及使用
  12. SHELL字符串使用总结
  13. C mysql带参数存储过程_C# 调用Mysql 带参数存储过程
  14. oracle分区索引优化,SQL优化思路结果集重用优化、分区索引优化测试
  15. 哈佛幸福课中提到的书_借助虚拟现实,在哈佛最大的班级中排在前列
  16. frame和bounds的区别
  17. cubieboard上手
  18. Presenting view controllers on detached view controllers is discouraged
  19. chatter个人理解
  20. C predefined macros __FILE__,__LINE__,__func__

热门文章

  1. QML实现的简单图文编辑器
  2. IFC中的聚合关系(IfcRelAggregates)
  3. 遗传转化的基本知识(四)——植物遗传转化的载体系统
  4. 快、狠、准排查各类系统故障的运维套路
  5. matlab 中sin60 怎么打,已知60=x*2*sin(pi*74/(4*x)),用matlab解此方程的语句该怎么写?
  6. 自己电脑上装的一些辅助软件
  7. 竣达技术丨中小型机房动环网络监控主机解决方案
  8. 判断两个IP是否在同一网段
  9. 从AI到BI,全面解读人工智能与商业智能
  10. 职能部门是否可以不参加绩效考核?