在开发过程中发现model或者po层的数据只是参数不同,其他都是一样,而每次编写的时候同样的事情需要花费很多的时间去写或者拷贝。虽然有些能够快速生成,但是还是需要时间,比如Parcelable接口实现的时候需要写一些东西,现在使用一个对文件编写的类来自动生成文件相信能减少更多的时间。甚至如果开发的接口够规范的话还能直接解析接口生成model或者po文件。
源码如下:
import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.util.Date;
/**
* 在指定位置生成model或者po文件
*
* @author xiaoyi
*
* 2015年3月6日
*/
public class CreateMode {
/**
* 指定文件路径
*/
public static String dirPath = "C:\\Users\\chengxuyuan2\\Desktop\\model";
/**
* 指定文件格式
*/
public static String byteType = "GBK";
/**
* 在指定位置判断并创建文件和文件夹
*
* @param dir
* 指定的文件夹
* @param file
* 指定的文件
* @return
* @throws Exception
*/
public static void createFile(File dir, File file) throws Exception {
try {
// 在指定位置判断并创建文件夹
if (dir.exists()) {
System.out.println("model文件夹存在");
} else {
System.out.println("model文件夹不存在,创建model");
dir.mkdir();// 不存在则创建
}
// 在指定位置判断并创建文件
if (file.exists()) {
System.out.println(file.getName() + "文件存在");
} else {
System.out
.println(file.getName() + "文件不存在,新建" + file.getName());
file.createNewFile();// 不存在则创建
}
} catch (Exception e) {
System.out.println(file.getName() + "文件创建失败!");
e.printStackTrace();
}
}
/**
* 对指定文件中写入指定内容
*
* @param content
* 写入内容
* @param dirPath
* 文件路径
* @param fileName
* 文件名称
* @param byteType
* 写入格式 GBK,UTF-8...
* @return
* @throws Exception
*/
public static boolean writeTxtFile(StringBuilder content, String dirPath,
String fileName, String byteType) throws Exception {
File dir = new File(dirPath);
File file = new File(dir, fileName);
createFile(dir, file);
RandomAccessFile mm = null;
boolean flag = false;
FileOutputStream o = null;
try {
o = new FileOutputStream(file);
o.write(content.toString().getBytes(byteType));
o.close();
flag = true;
} catch (Exception e) {
System.out.println("文件内容写入失败!");
e.printStackTrace();
} finally {
if (mm != null) {
mm