您的位置:首页 > 编程语言 > Java开发

java实现文件的创建

2011-05-09 15:24 357 查看
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@SuppressWarnings("unused")
public class createFile {

/**
* @param args
*/

// 创建目标文件
@SuppressWarnings("static-access")
public static boolean createFile(String filePath) {
File file = new File(filePath);
if (file.exists()) {
System.out.println("目标文件已经存在" + filePath);
System.err.println("日志信息:目标文件已经存在"+filePath+"日志日期:"+new SimpleDateFormat("yyyy/MM/dd:HH:mm:ss").format(new Date()));
return false;
}
// 判断文件是否为目录
if (filePath.endsWith(file.separator)) {
System.out.println("目标文件不能为目录!");
}
if (!file.getParentFile().exists()) {// 判断目标文件所在的目录是否存在
System.out.println("目标文件所在的目录不存在,准备创建!");
if (!file.getParentFile().mkdirs()) {// 判断创建目录是否成功
System.out.println("创建目标文件所在的目录失败!");
return false;
}
}
try {
// 创建文件
if (file.createNewFile()) {
System.out.println("创建文件成功:" + filePath);
return true;
} else {
System.out.println("创建文件失败!");
return false;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("创建文件失败!" + e.getMessage());

return false;
}
}

// 创建目录
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
System.out.println("创建目录失败!" + dir.getPath());
return false;
}
if (destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
if (dir.mkdirs()) {
System.out.println("创建目录成功!" + destDirName);
return true;

} else {
System.out.println("创建目录失败!");
return false;
}
}
//创建临时文件
public static String createTempFile(String prefix,String suffix,String dirName){
File tempFile= null;
if (dirName==null) {
try {
tempFile=File.createTempFile(prefix, suffix);
return tempFile.getCanonicalPath();
} catch (Exception e) {
System.out.println("创建临时文件失败:"+e.getMessage());
return null;
}
}else{
File dir=new File(dirName);
if (!dir.exists()) {
if (createFile.createDir(dirName)) {
System.out.println("创建临时文件失败,不能创建临时文件所在的目录!");
return null;
}
}
try {
tempFile=File.createTempFile(prefix, suffix,dir);
return tempFile.getCanonicalPath();
} catch (Exception e) {
e.getStackTrace();
System.out.println("创建临时文件失败!"+e.getMessage());
return null;
}
}
}

@SuppressWarnings("static-access")
public static void main(String[] args) {
createFile create = new createFile();
create.createFile("d://create//temp.txt");
create.createDir("d://create2//");
String prefix="temp";
String suffix=".txt";
for (int i = 0; i < 10; i++) {
System.out.println("您创建的临时文件为:"+create.createTempFile(prefix, suffix, "d://create2//"));
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐