Java IO流各种使用方式总结
①针对普通文本的复制常用方式:
FileInputStream fis = new FileInputStream(tempFile);
FileOutputStream fos = new FileOutputStream(new File(dest));
byte[] buff = new byte[1024];
int len = -1;
while ((len = fis.read(buff)) != -1) {
fos.write(buff, 0, len);
}
fis.close();
fos.flush();
fos.close();
②效率比较高的复制方式:
第一种用法/*2、用新IO里的FileChannel方式*/
FileChannel srcCh = new FileInputStream(src).getChannel();
FileChannel destCh = new FileOutputStream(dest).getChannel();
destCh.transferFrom(srcCh, 0, srcCh.size());
srcCh.close();
destCh.close();第二种用法 fIn = new FileInputStream(args[0]);
fOut = new FileOutputStream(args[1]);
fIChan = fIn.getChannel();
fOChan = fOut.getChannel();
fSize = fIChan.size();
mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);
fOChan.write(mBuf); // this copies the file
fIChan.close();
fIn.close();
③删除N天前的文件(定期删备份文件)比如删除目录中超过一个星期的所有文本文件/**
* 删除备份数据库文件 注意:指定删除的文件为最后一次修改的文件日期,不是按照文件名也不是
* 文件所创建的日期。指定的path必须是目录名,否则函数不会执行并且没有返回值。
*
* @param day
* 天数
* @param path
* 路径目录名
*/
public static void deletedb(int day, String path) {
long datenum;
Date date;
Date datenow;
Calendar cal = Calendar.getInstance();
Calendar calnow = Calendar.getInstance();
File filepath = CsvOperate.filepathpreproc(path);
File[] files;
if (filepath.exists()) {
if (filepath.isDirectory()) {
files = filepath.listFiles();
for (int i = 0; i < files.length; i++) {
date = new Date(files[i].lastModified());
datenow = new Date();
cal.setTime(date);
calnow.setTime(datenow);
int dec = calnow.get(Calendar.DAY_OF_YEAR)
- cal.get(Calendar.DAY_OF_YEAR);
// 删除指定日期的文件
if (dec >= day) {
files[i].delete();
}
} // end for
} // end if (filepath.isdirectory())
} // end if (filepath.exists())
}
/**
* 文件路径预处理,将windows或unix like 路径转化为统一的unix like路径,如果用户输入有误则返回null
*
* @param pathstr
* @return
*/
public static File filepathpreproc(String pathstr) {
pathstr = pathstr.replaceAll(" \\\\", "/").trim();
// system.out.println(pathstr);
Pattern p = Pattern.compile("(^\\.|^/|^[a-za-z])?:?/.+(/$)?");
Matcher m = p.matcher(pathstr);
// 不符合要求直接返回
if (!m.matches()) {
return null;
}
// 这里开始文件名已经符合要求
File path = new File(pathstr);
return path;
}④另奉完整复制示例public class PrintFiles {
String sourcDir = "";
String desDir = "";
File file = null;
String logFile = "";
public PrintFiles(String root,String sourcDir,String desDir,String logFile){
this.file = new File(root);
this.sourcDir = sourcDir;
this.desDir = desDir;
this.logFile = logFile;
}
/*
* @method检查指定的源目的文件夹是否存在
*/
public int checkDirName(){
File [] fileArray = file.listFiles();
boolean flag_desDir = false;
boolean flag_sourceDir = false;
for(int i=0;i<fileArray.length;i++){
if(fileArray[i].getName().equalsIgnoreCase(sourcDir)){
flag_sourceDir = true;
}
if(fileArray[i].getName().equalsIgnoreCase(desDir)){
flag_desDir = true;
}
if(flag_desDir&&flag_sourceDir){
break;
}
}
if(!flag_desDir){
File d = new File(file.toString().replace('\\', '/')+desDir);
d.mkdir();
}
if(!flag_sourceDir){
return 1;
}
return 2;
}
/*
* @method执行文件拷贝功能
*/
public String copyFiles(){
String root = file.toString().replace( '\\' , '/');
File [] fileArray = new File(root+sourcDir).listFiles();
for(int i=0;i<fileArray.length;i++){
String filename = fileArray[i].getName();
if(filename.endsWith(".txt")){
try {
FileInputStream fileInputStream = new FileInputStream(root+sourcDir+"/"+filename);
FileOutputStream fileOutputStream = new FileOutputStream(root+desDir+"/"+filename);
byte [] b = new byte[1024*5];
int len;
while((len=fileInputStream.read(b))!=-1){
fileOutputStream.write(b, 0, len);
}
fileOutputStream.flush();
fileOutputStream.close();
fileInputStream.close();
writeToLog(root+"/"+logFile, filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
return "FileNotFoundException";
}catch(IOException e){
e.printStackTrace();
return "IOException";
}}}
return "OK";
}
/*
* @method写入日志
*/
public String writeToLog(String logName,String data){
File logfile = new File(logName);
if(!logfile.exists()){
try{
logfile.createNewFile();
}catch(IOException e){
e.printStackTrace();
}
}else{
StringBuffer sb = new StringBuffer();
try{
if (data != null && data.length() > 0){
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(logfile)));
String tempdata = null;
while((tempdata=br.readLine())!= null){
sb.append(tempdata+"\n");
}
br.close();
}
PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(logfile)), true);
pw.write(sb.toString());
pw.write(data);
pw.flush();
pw.close();
}catch(Exception e){
e.printStackTrace();
}
}
return "";
}
public static void main(String[] args) throws Exception {
String copy = "";
PrintFiles pf = new PrintFiles("e:/","wx1","wx2","ss.log");
int i = pf.checkDirName();
if(i==1){
System.out.println("源文件夹不存在");
}else if(i==2){
System.out.println("完成检查");
copy = pf.copyFiles();
System.out.println("拷贝检查");
}
if(copy.equalsIgnoreCase("FileNotFoundException")){
System.out.println("FileNotFoundException");
}else if(copy.equalsIgnoreCase("IOException")){
System.out.println("IOException");
}
}
}