近日闲来无事看一些资料,一些有用的资料都是影印版的,想在上面做笔记无从下手,想到了把这些转换成word,但影印版的pdf转换成word非常麻烦,需要把影印的资料从pdf中提取出来,然后再用汉王等软件把提取出来的图片转换成word。但转换工具对图片格式有要求,比如:bmp、rtf等,而得到图片都是jpg格式的,有500多张需要全部转换。第一时间想到了在网上找转换图片格式的软件,寻找过程中发现有人通过Java代码实现了这一功能。这让一直在用Java的我汗颜:我怎么没想到呢,我也要写出来(虽然大多数情况下不要重复发明轮子)。其实也很简单,只需要简单的几句话就行,但发现写好不容易,只是改了文件的后缀名,并没有真正修改文件格式
ChangeFileFormat.java
import java.io.File;
public class ChangeFileFormat {
public static void main(String args[]) {
long start = System.currentTimeMillis();
String format1 = ReadProperties.getProperty("beforeFormat");
String format2 = ReadProperties.getProperty("afterFormat");
String fileName = ReadProperties.getProperty("dir");
changeFormat(fileName, format1, format2);
long end = System.currentTimeMillis();
System.out.println("共耗时:" + (end - start));
}
public static void changeFormat(String fileName, String beforeFormat,
String afterFormat) {
File file = new File(fileName);
if (file.exists()) {
String fileRoot = file.getAbsolutePath(); // D:\1
String[] arr = file.list(); // 取得目录下所有的文件( 数组的形式)
if (arr != null && arr.length > 0) { // 遍历数组
for (int i = 0; i < arr.length; i++) {
if (arr[i].substring(arr[i].length() - 3, arr[i].length())
.equals(beforeFormat)) {
File tempFile = new File(fileRoot + "//" + arr[i]); // 获得某个具体的文件
// 修改格式
String str = arr[i].replaceAll(beforeFormat,
afterFormat);
boolean b = tempFile.renameTo(new File(fileRoot + "//"
+ str));
// 判断是否成功
if (b) {
System.out.println("ok");
} else {
System.out.println("wrong");
}
}
}
}
} else {
System.out.println("所指定的目录不存在,将为你创建指定的目录");
file.mkdir();
}
}
}
ReadProperties.java
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ReadProperties {
private static final String fileName = "resource.properties";
private static final Properties properties = new Properties();
private static final Log log = LogFactory.getLog(ReadProperties.class); //需要commons-logging-1.1.1.jar
static {
try {
//从输入流中读取属性列表(键和元素对)
properties.load(ReadProperties.class.getResourceAsStream(fileName));
} catch (IOException e) {
log.error("读取配置文件出错: " + fileName);
e.printStackTrace();
}
}
public static String getProperty(String key) {
// getProperty(String key) ----- 用指定的键在此属性列表中搜索属性
return properties.getProperty(key) != null ? properties.getProperty(key) : null;
}
}
resource.properties
#转换前的格式
beforeFormat=jpg
#转换后的格式
afterFormat=bmp
#文件目录
dir=d:/2
2476

被折叠的 条评论
为什么被折叠?



