
正文:
文件格式一般可分为:①文档格式、②图片格式、③视频格式、④声音格式、⑤系统格式。
具体如下:
一、文档格式有:TXT、DOC、DOCX、XLS、PPT、XLSX、PPTX 等。
二、图片格式有:JPG、PNG、PDF、TIFF、SWF等。
三、视频格式有:FLV、RMVB、MP4、MVB等。
四、声音格式有:WMA、MP3等。
五、系统格式有:RAR、EXE等。
这里只讨论前2种。
(1).操作TXT
-
-
- package com.chunbaosheng.demo;
-
- import java.io.*;
-
- public class TestOne {
- //使用FileInputStream实现读取txt文件内容:
- //使用FileOutputStream实现写入txt文件内容:
-
- /**传入txt路径读取txt文件
- * @param txtPath
- * @return 返回读取到的内容
- */
- public static String readTxt(String txtPath) {
- File file = new File(txtPath);
- if (file.isFile() && file.exists()) {
- try {
- FileInputStream fileInputStream = new FileInputStream(file);
- InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
- BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
-
- StringBuffer sb = new StringBuffer();
- String text = null;
- while ((text = bufferedReader.readLine()) != null) {
- sb.append(text);
- }
- return sb.toString();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- return null;
- }
-
-
- /**使用FileOutputStream来写入txt文件
- * @param txtPath txt文件路径
- * @param content 需要写入的文本
- */
- public static void writeTxt(String txtPath,String content){
- FileOutputStream fileOutputStream = null;
- File file = new File(txtPath);
- try {
- if(file.exists()){
- //判断文件是否存在,如果不存在就新建一个txt
- file.createNewFile();
- }
- fileOutputStream = new FileOutputStream(file);
- fileOutputStream.write(content.getBytes());
- fileOutputStream.flush();
- fileOutputStream.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
- //验证方法:先写入文件后读取打印如下:
- public static void main(String[] args) {
- writeTxt("C:\\Users\\Administrator\\Desktop\\1\\result1.txt", "测试写入txt文件内容");
- String str = readTxt("C:\\Users\\Administrator\\Desktop\\1\\result1.txt");
- System.out.println(str);
- }
-
-
- }
(2).操作Doc/Docx 文档
-
- <dependency>
- <groupId>org.apache.poigroupId>
- <artifactId>poi-scratchpadartifactId>
- <version>3.14version>
- dependency>
- <dependency>
- <groupId>commons-iogroupId>
- <artifactId>commons-ioartifactId>
- <version>2.6version>
- dependency>
- <dependency>
- <groupId>org.apache.poigroupId>
- <artifactId>poi-ooxmlartifactId>
- <version>3.14version>
- dependency>
读:
- package com.chunbaosheng.demo;
-
-
-
- import org.apache.poi.POIXMLDocument;
- import org.apache.poi.POIXMLTextExtractor;
- import org.apache.poi.hwpf.extractor.WordExtractor;
- import org.apache.poi.openxml4j.opc.OPCPackage;
- import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
-
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.util.ArrayList;
- import java.util.List;
-
-
- public class TestTwo {
- /**
- * @Description: POI 读取 word
- * @update logs
- * @throws Exception
- */
- public static List
readWord(String filePath) throws Exception{ -
- List
linList = new ArrayList(); - String buffer = "";
- try {
- if (filePath.endsWith(".doc")) {
- InputStream is = new FileInputStream(new File(filePath));
- WordExtractor ex = new WordExtractor(is);
- buffer = ex.getText();
- is.close();
-
- if(buffer.length() > 0){
- //使用回车换行符分割字符串
- String [] arry = buffer.split("\\r\\n");
- for (String string : arry) {
- linList.add(string.trim());
- }
- }
- } else if (filePath.endsWith(".docx")) {
- System.out.println("读取docx");
- OPCPackage opcPackage = POIXMLDocument.openPackage(filePath);
- POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
- buffer = extractor.getText();
- extractor.close();
-
-
- if(buffer.length() > 0){
- //使用换行符分割字符串
- String [] arry = buffer.split("\\n");
- for (String string : arry) {
- System.out.println(string);
- linList.add(string.trim());
- }
- }
- } else {
- return null;
- }
-
- return linList;
- } catch (Exception e) {
- System.out.print("error---->"+filePath);
- e.printStackTrace();
- return null;
- }
- }
-
- public static void main(String[] args)throws Exception {
- System.out.println(readWord("C:\\Users\\Administrator\\Desktop\\1\\Java面试宝典.docx"));
- }
-
- }
写:
- package com.chunbaosheng.demo;
-
- import org.apache.poi.hwpf.HWPFDocument;
- import java.io.*;
-
-
- public class WriteDoc {
- public static void testWrite() throws Exception {
-
-
- String templatePath = "C:\\Users\\Administrator\\Desktop\\1\\template.doc";
- InputStream is = new FileInputStream(templatePath);
- OutputStream os = null;
- HWPFDocument doc = new HWPFDocument(is);
-
- os = new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\1\\template1.doc"));
- //把doc输出到输出流中
- doc.write(os);
-
- os.close();
- // is.close();
- }
-
- public static void main(String[] args) throws Exception{
- testWrite();
- }
-
-
- }
操作:XLS,XLSX
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>easyexcelartifactId>
- <version>2.2.3version>
- dependency>
写:
- // 根据user模板构建数据
- private List
getUserData() { - List
users = new ArrayList<>(); - for (int i = 1; i <= 10; i++) {
- User user = User.builder()
- .userId(i)
- .userName("admin" + i)
- .gender(i % 2 == 0 ? "男" : "女")
- .salary(i * 1000.00)
- .hireDate(new Date())
- .build();
- users.add(user);
- }
- return users;
- }
-
-
- @Test
- public void testWriteExcel() {
-
- String filename = "D:\\study\\excel\\user1.xlsx";
-
- // 向Excel中写入数据 也可以通过 head(Class>) 指定数据模板
- EasyExcel.write(filename, User.class)
- .sheet("用户信息")
- .doWrite(getUserData());
- }
读:
- @Test
- public void testReadExcel() {
- // 读取的excel文件路径
- String filename = "D:\\study\\excel\\read.xlsx";
- // 读取excel
- EasyExcel.read(filename, DemoData.class, new AnalysisEventListener
() { - // 每解析一行数据,该方法会被调用一次
- @Override
- public void invoke(DemoData demoData, AnalysisContext analysisContext) {
- System.out.println("解析数据为:" + demoData.toString());
- }
- // 全部解析完成被调用
- @Override
- public void doAfterAllAnalysed(AnalysisContext analysisContext) {
- System.out.println("解析完成...");
- // 可以将解析的数据保存到数据库
- }
- }).sheet().doRead();
- }
-
-
- //读excel的方式二代码
-
- @Test
- public void testReadExcel2() {
- // 读取的excel文件路径
- String filename = "D:\\study\\excel\\read.xlsx";
- // 创建一个数据格式来装读取到的数据
- Class
head = DemoData.class; - // 创建ExcelReader对象
- ExcelReader excelReader = EasyExcel.read(filename, head, new AnalysisEventListener
() { - // 每解析一行数据,该方法会被调用一次
- @Override
- public void invoke(DemoData demoData, AnalysisContext analysisContext) {
- System.out.println("解析数据为:" + demoData.toString());
- }
- // 全部解析完成被调用
- @Override
- public void doAfterAllAnalysed(AnalysisContext analysisContext) {
- System.out.println("解析完成...");
- // 可以将解析的数据保存到数据库
- }
- }).build();
- // 创建sheet对象,并读取Excel的第一个sheet(下标从0开始), 也可以根据sheet名称获取
- ReadSheet sheet = EasyExcel.readSheet(0).build();
- // 读取sheet表格数据, 参数是可变参数,可以读取多个sheet
- excelReader.read(sheet);
- // 需要自己关闭流操作,在读取文件时会创建临时文件,如果不关闭,会损耗磁盘,严重的磁盘爆掉
- excelReader.finish();
- }
操作 PPT、PPTX
写
- //Java基于POI对PPT的基本操作
- // 在Java中对PPT文件进行操作的话,我使用的是Apache的开源项目POI。该项目的功能主要是使用
- //Java开发或生成微软办公文件,比如:Word、Excel、PPT、Visio等。其中实现对PPT文件进行操作的类包
- //主要是HSLF(.ppt)和XSLF(.pptx),在本文中,会以XSLF为主。
- //创建PPT文件,并生成空白幻灯片
- package com.jointstarc.test;
-
-
-
- import java.io.FileOutputStream;
-
- import java.io.IOException;
-
-
-
- import org.apache.poi.xslf.usermodel.XMLSlideShow;
-
- import org.apache.poi.xslf.usermodel.XSLFSlide;
-
-
-
- public class Demo1 {
-
- public static void main(String[] args) {
-
- // 创建一个空白PPT
-
- XMLSlideShow ppt = new XMLSlideShow();
-
- // 在空白的PPT中创建一个空白的幻灯片
-
- XSLFSlide slide = ppt.createSlide();
-
- try {
-
- // 对新建的PPT保存到硬盘里
-
- ppt.write(new FileOutputStream("D://test3.pptx"));
-
- } catch (Exception e) {
-
- e.printStackTrace();
-
- } finally {
-
- if (ppt != null) {
-
- try {
-
- // 保存完之后要对PPT进行关闭操作
-
- ppt.close();
-
- } catch (IOException e) {
-
- e.printStackTrace();
-
- }
-
- }
-
- }
-
- }
-
- }
- //添加文本框和超链接
- /*
- * 在空幻灯片中插入一个文本框,然后在文本框中写入文字,
- * 并给文字添加一个超链接
- */
-
- // 在幻灯片中插入一个文本框
-
- XSLFTextShape ts = slide.createTextBox();
-
- // 设置文本框的位置和文本框大小
-
- ts.setAnchor(new Rectangle(150, 150, 200, 50));
-
- // 设置文本框里面的文字
-
- XSLFTextRun tr = ts.addNewTextParagraph().addNewTextRun();
-
- tr.setText("测试一下");
-
- // 给文本添加颜色
-
- tr.setFontColor(Color.RED);
-
- // 给文本添加超链接
-
- XSLFHyperlink link = tr.createHyperlink();
-
- link.setAddress("http://www.baidu.com");
- /*
- * 在幻灯片中添加表格
- */
-
- // 在幻灯片中插入一个表格
-
- XSLFTable table = slide1.createTable();
-
- // 设置表格的位置和表格大小
-
- table.setAnchor(new Rectangle(50, 100, 100, 100));
-
- for (int i = 0; i < 5; i++) {
-
- // 在表格中添加一行
-
- XSLFTableRow row = table.addRow();
-
- for (int j = 0; j < 5; j++) {
-
- // 在行中添加一个单元格
-
- XSLFTableCell cell = row.addCell();
-
- // 设置单元格中的内容和样式
-
- XSLFTextParagraph p = cell.addNewTextParagraph();
-
- p.setTextAlign(TextAlign.CENTER);
-
- XSLFTextRun tr1 = p.addNewTextRun();
-
- tr1.setFontColor(Color.RED);
-
- tr1.setText("测试" + i + j);
-
- // 设置单元格边框的粗细
-
- cell.setBorderWidth(BorderEdge.bottom, 2.0);
-
- cell.setBorderWidth(BorderEdge.left, 2.0);
-
- cell.setBorderWidth(BorderEdge.right, 2.0);
-
- cell.setBorderWidth(BorderEdge.top, 2.0);
-
- // 设置单元格边框的颜色
-
- cell.setBorderColor(BorderEdge.bottom, Color.black);
-
- cell.setBorderColor(BorderEdge.left, Color.black);
-
- cell.setBorderColor(BorderEdge.right, Color.black);
-
- cell.setBorderColor(BorderEdge.top, Color.black);
-
- }
-
- }
- /*
- * 在幻灯片中插入一张图片
- */
-
- // 图片文件
-
- File image = new File("D://111.jpg");
-
- // 图片文件输入流
-
- FileInputStream imageFis = new FileInputStream(image);
-
- // 获取图片大小
-
- int len = (int) image.length();
-
- // 创建一个字节数组,数组大小与图片文件大小一致
-
- byte[] imageData = new byte[len];
-
- // 将图片数据读进字节数组中
-
- imageFis.read(imageData);
-
- // 将图片添加到PPT中
-
- XSLFPictureData pd = ppt.addPicture(imageData, PictureData.PictureType.JPEG);
-
- // 将图片放到指定的幻灯片中
-
- XSLFPictureShape pic = slide2.createPicture(pd);
-
- // 设置图片框的放置的位置和大小
-
- pic.setAnchor(new Rectangle(50, 100, 200, 200));
-
- package com.jointstarc.test;
-
-
-
- import java.io.FileInputStream;
-
- import java.io.FileOutputStream;
-
- import java.io.IOException;
-
-
-
- import org.apache.poi.xslf.usermodel.XMLSlideShow;
-
- import org.apache.poi.xslf.usermodel.XSLFSlide;
-
-
-
- public class Demo2 {
-
- public static void main(String[] args) {
-
- XMLSlideShow ppt = null;
-
- try {
-
- // 通过输入流读取一个现有的PPT文件,生成PPT类
-
- ppt = new XMLSlideShow(new FileInputStream("D://test.pptx"));
-
- // 在现有的PPT文件后面新建一个空白幻灯片
-
- XSLFSlide slide = ppt.createSlide();
-
- // 将修改后的PPT文件回写到硬盘
-
- ppt.write(new FileOutputStream("D://test3.pptx"));
-
- } catch (Exception e) {
-
- e.printStackTrace();
-
- } finally {
-
- if (ppt != null) {
-
- try {
-
- // 保存完之后要对PPT进行关闭操作
-
- ppt.close();
-
- } catch (IOException e) {
-
- e.printStackTrace();
-
- }
-
- }
-
- }
-
- }
-
- }
- /*
- * 获取PPT的所有文本框里的文字,并进行更改
- */
-
- // 获取PPT中的所有幻灯片
-
- List
slides = ppt.getSlides(); -
- // 遍历幻灯片
-
- for (XSLFSlide slide : slides) {
-
- // 获取幻灯片中的所有图形(文本框、表格、图形...)
-
- List
shapes = slide.getShapes(); -
- // 遍历图形
-
- for (XSLFShape shape : shapes) {
-
- // 判断该图形类是否是文本框类
-
- if (shape instanceof XSLFTextShape) {
-
- // 将图像类强制装换成文本框类
-
- XSLFTextShape ts = (XSLFTextShape) shape;
-
- // 获取文本框内的文字
-
- String str = ts.getText();
-
- System.out.println(str);
-
-
-
- // 若想对文本框内的文字进行更改,还需要进行如下步骤
-
- List
textParagraphs = ts.getTextParagraphs(); -
- for (XSLFTextParagraph tp : textParagraphs) {
-
- List
textRuns = tp.getTextRuns(); -
- for (XSLFTextRun r : textRuns) {
-
- if ("201809".equals(r.getRawText())) {
-
- // 对匹配到的字符串进行更改
-
- r.setText("2018-09");
-
- // 设置字体颜色
-
- r.setFontColor(Color.RED);
-
- }
-
- }
-
- }
-
- }
-
- }
-
- }
- /*
- * 获取PPT的所有表格里的文字,并进行更改
- */
-
- // 获取PPT中的所有幻灯片
-
- List
slides = ppt.getSlides(); -
- for (XSLFSlide slide : slides) {
-
- // 获取幻灯片中的所有图形(文本框、表格、图形...)
-
- List
shapes = slide.getShapes(); -
- for (XSLFShape shape : shapes) {
-
- // 判断该图形类是否是表格类
-
- if (shape instanceof XSLFTable) {
-
- // 将图像类强制装换成表格类
-
- XSLFTable table = (XSLFTable) shape;
-
- // 获取表格中的所有行
-
- List
rows = table.getRows(); -
- for (XSLFTableRow tr : rows) {
-
- // 获取行中的所有单元格
-
- List
cells = tr.getCells(); -
- for (XSLFTableCell tc : cells) {
-
- // 获取单元格内的文字
-
- String str = tc.getText();
-
- // 若想对表格内的文字进行更改,还需要进行如下步骤
-
- List
textParagraphs = tc.getTextParagraphs(); -
- for (XSLFTextParagraph tp : textParagraphs) {
-
- List
textRuns = tp.getTextRuns(); -
- for (XSLFTextRun r : textRuns) {
-
- if ("风险指标".equals(r.getRawText())) {
-
- // 对匹配到的字符串进行更改
-
- r.setText("测试修改文字");
-
- // 设置字体颜色
-
- r.setFontColor(Color.RED);
-
- }
-
- }
-
- }
-
- }
-
- }
-
- }
-
- }
-
- }
- /*
- * 获取PPT的所有图片,并进行更改
- */
-
- // 获取PPT中的所有幻灯片
-
- List
slides = ppt.getSlides(); -
- for (XSLFSlide slide : slides) {
-
- // 获取幻灯片中的所有图形(文本框、表格、图形...)
-
- List
shapes = slide.getShapes(); -
- for (XSLFShape shape : shapes) {
-
- // 判断该图形类是否是图片框类
-
- if (shape instanceof XSLFPictureShape) {
-
- /*
- * 获取图片数据
- */
-
- // 将图像类强制装换成图片框类
-
- XSLFPictureShape ps = (XSLFPictureShape) shape;
-
- // 获取图片的字节码数据(可以利用输出流将该图片保存到硬盘里)
-
- byte [] pictureData = ps.getPictureData().getData();
-
- /*
- * 更改图片
- */
-
- // 图片文件
-
- File image = new File("D://222.jpg");
-
- // 图片文件输入流
-
- FileInputStream imageFis = new FileInputStream(image);
-
- // 获取图片大小
-
- int len = (int) image.length();
-
- // 创建一个字节数组,数组大小与图片文件大小一致
-
- byte[] imageData = new byte[len];
-
-
-
- if (imageFis.read(imageData) != -1) {
-
- // 更换图片必须图片设置索引,要不不生效
-
- ps.getPictureData().setIndex(1);
-
- ps.getPictureData().setData(imageData);
-
- }
-
- // 关闭输入流
-
- imageFis.close();
-
- }
-
- }
-
- }
操作图片格式有:JPG、PNG、PDF、TIFF、SWF等。
-
-
-
org.icepdf.os -
icepdf-core -
6.1.2 -
-
-
javax.media -
jai-core -
-
-
-
Pdf文件转图片方法
- import org.apache.pdfbox.pdmodel.PDDocument;
- import org.apache.pdfbox.pdmodel.PDPageTree;
- import org.apache.pdfbox.rendering.PDFRenderer;
-
- import javax.imageio.ImageIO;
- import java.awt.image.BufferedImage;
- import java.io.*;
-
- public class PdfToImgOne {
- /**
- * pdfToImageFile("E:\\pdf\\1.pdf", "E:\\pdf\\img\\");
- * @param inputFilePath :Pdf地址:"E:\\pdf\\1.pdf"
- * @param outputFilePath :转图片后图片保存地址:"E:\\pdf\\img\\"
- * @throws Exception
- */
- static void pdfToImageFile(String inputFilePath, String outputFilePath) throws Exception {
- long currentTimeMillisStart = System.currentTimeMillis();
- PDDocument doc = null;
- ByteArrayOutputStream os = null;
- InputStream stream = null;
- OutputStream out = null;
- try {
- // pdf路径
- stream = new FileInputStream(inputFilePath);
- // 加载解析PDF文件
- doc = PDDocument.load(stream);
- PDFRenderer pdfRenderer = new PDFRenderer(doc);
- PDPageTree pages = doc.getPages();
- int pageCount = pages.getCount();
- for (int i = 0; i < pageCount; i++) {
- BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200);
- os = new ByteArrayOutputStream();
- ImageIO.write(bim, "jpg", os);
- byte[] dataList = os.toByteArray();
- // jpg文件转出路径
- File file = new File(outputFilePath + Integer.valueOf(i + 1) + ".jpg");
- if (!file.getParentFile().exists()) {
- // 不存在则创建父目录及子文件
- file.getParentFile().mkdirs();
- file.createNewFile();
- }
- out = new FileOutputStream(file);
- out.write(dataList);
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw e;
- } finally {
- if (doc != null) doc.close();
- if (os != null) os.close();
- if (stream != null) stream.close();
- if (out != null) out.close();
- }
- long currentTimeMillisEnd = System.currentTimeMillis();
- System.out.println("18页的Pdf转换完成耗时:"
- +(currentTimeMillisEnd - currentTimeMillisStart)/1000);//18页的Pdf转换完成耗时:6
- }
- }