从指定目录读取doc文件,批量转换为docx格式,输出到指定目录
仅做技术探讨,个人使用涉及侵权问题,与本人无关
package ext.poi.word;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
//从指定目录读取doc文件,转换为docx格式,输出到指定目录
public class DocCastDocx {
public static void main(String[] args) {
//String inPath="C:\\formatConversion\\input\\test.doc";
//String outPath="C:\\formatConversion\\output\\test.docx";
String inPath="";
String outPath="";
String path="C:\\formatConversion\\input";
String path2="C:\\formatConversion\\output";
File file =new File(path);
List<String> filelist = new ArrayList();
filelist=getFile(file,filelist);
if(filelist.size()==0) {
System.out.println("该目录下不存在文件");
}else {
for(String f : filelist) {
int index = f.indexOf(".");//获取第一个"."的位置3
String str = f.substring(0,index);//不含".",这叫含头不含尾
//System.out.println("文件名:"+str);
outPath=path2+"\\"+str+".docx";
inPath=path+"\\"+f;
System.out.println("读取的目录:"+inPath);
System.out.println("输出的目录:"+outPath);
doc2pdf(inPath,outPath);
}
}
}
public static boolean getLicense() {
boolean result = false;
try {
//这个地方xml文件的路径要写正确,从src目录下的包开始
Resource resource = new ClassPathResource("ext\\poi\\word\\license.xml");
InputStream is = resource.getInputStream();
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void doc2pdf(String inPath, String outPath) {
if (!getLicense()) {
return;
}
try {
File file = new File(outPath);
FileOutputStream os = new FileOutputStream(file);
Document doc = new Document(inPath);
doc.save(os, SaveFormat.DOCX);// 这里可以写你想要装换的类型:DOC, DOCX, PDF,HTML
} catch (Exception e) {
e.printStackTrace();
}
}
//读取制定目录下的所有文件,返回文件名的list集合
private static List<String> getFile(File file,List<String> fileList) {
if(!file.exists()) {
return null;
}
File[] files = file.listFiles();
for(File f : files) {
if(f.isDirectory()) {
getFile(f,fileList);
}else {
fileList.add(f.getName());
}
}
return fileList;
}
}
在项目某位置新建一个license.xml文件,并复制下面内容复制到文件里就可以了。
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>
要添加转换格式的jar
aspose-words-15.12.0-jdk16.jar
链接: https://pan.baidu.com/s/10fYVVzExam28q8VoF4bW5A?pwd=rqsc
提取码: rqsc 复制这段内容后打开百度网盘手机App,操作更方便哦
–来自百度网盘超级会员v4的分享