java生成文件夹和文件的简单示例分享
实现文件夹和文件生成
package com.gotobus.common;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
public class jfile {
public static boolean createfile(string destfilename) {
file file = new file(destfilename);
if(file.exists()) {
return false;
}
if (destfilename.endswith(file.separator)) {
return false;
}
if(!file.getparentfile().exists()) {
if(!file.getparentfile().mkdirs()) {
return false;
}
}
try {
if (file.createnewfile()) {
return true;
} else {
return false;
}
} catch (ioexception e) {
e.printstacktrace();
return false;
}
}
public static boolean createdir(string destdirname) {
file dir = new file(destdirname);
if (dir.exists()) {
return false;
}
if (!destdirname.endswith(file.separator)) {
destdirname = destdirname + file.separator;
}
if (dir.mkdirs()) {
return true;
} else {
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 (ioexception e) {
e.printstacktrace();
return null;
}
} else {
file dir = new file(dirname);
if (!dir.exists()) {
if (!jfile.createdir(dirname)) {
return null;
}
}
try {
tempfile = file.createtempfile(prefix, suffix, dir);
return tempfile.getcanonicalpath();
} catch (ioexception e) {
e.printstacktrace();
return null;
}
}
}
public static void copyfile(string oldpath, string newpath) {
try {
int bytesum = 0;
int byteread = 0;
file oldfile = new file(oldpath);
if (oldfile.exists()) {
inputstream instream = new fileinputstream(oldpath);
fileoutputstream fs = new fileoutputstream(newpath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = instream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
instream.close();
}
}
catch (exception e) {
e.printstacktrace();
}
}
}
上一篇: Java 关键字 速查表介绍