java文件和目录的增删复制
在使用java进行开发时常常会用到文件和目录的增删复制等方法。我写了一个小工具类。和大家分享,希望大家指正:
packagecom.wangpeng.utill; importjava.io.File; importjava.io.FileInputStream; importjava.io.FileOutputStream; importjava.io.FileWriter; importjava.io.InputStream; importjava.io.PrintWriter; /** *@authorwangpeng * */ publicclassToolOfFile{ /** *创建目录 * *@paramfolderPath *目录目录 *@throwsException */ publicstaticvoidnewFolder(StringfolderPath)throwsException{ try{ java.io.FilemyFolder=newjava.io.File(folderPath); if(!myFolder.exists()){ myFolder.mkdir(); } }catch(Exceptione){ throwe; } } /** *创建文件 * *@paramfilePath *文件路径 *@throwsException */ publicstaticvoidnewFile(StringfilePath)throwsException{ try{ FilemyFile=newFile(filePath); if(!myFile.exists()){ myFile.createNewFile(); } }catch(Exceptione){ throwe; } } /** *创建文件,并写入内容 * *@paramfilePath *文件路径 *@paramfileContent *被写入的文件内容 *@throwsException */ publicstaticvoidnewFile(StringfilePath,StringfileContent) throwsException{ //用来写入字符文件的便捷类 FileWriterfileWriter=null; //向文本输出流打印对象的格式化表示形式,使用指定文件创建不具有自己主动行刷新的新 PrintWriterprintWriter=null; try{ FilemyFile=newFile(filePath); if(!myFile.exists()){ myFile.createNewFile(); } fileWriter=newFileWriter(myFile); printWriter=newPrintWriter(fileWriter); printWriter.print(fileContent); printWriter.flush(); }catch(Exceptione){ throwe; }finally{ if(printWriter!=null){ printWriter.close(); } if(fileWriter!=null){ fileWriter.close(); } } } /** *复制文件 * *@paramoldPath *被拷贝的文件 *@paramnewPath *复制到的文件 *@throwsException */ publicstaticvoidcopyFile(StringoldPath,StringnewPath) throwsException{ InputStreaminStream=null; FileOutputStreamoutStream=null; try{ intbyteread=0; Fileoldfile=newFile(oldPath); //文件存在时 if(oldfile.exists()){ inStream=newFileInputStream(oldfile); outStream=newFileOutputStream(newPath); byte[]buffer=newbyte[1444]; while((byteread=inStream.read(buffer))!=-1){ outStream.write(buffer,0,byteread); } outStream.flush(); } }catch(Exceptione){ throwe; }finally{ if(outStream!=null){ outStream.close(); } if(inStream!=null){ inStream.close(); } } } /** *复制文件 *@paraminStream被拷贝的文件的输入流 *@paramnewPath被复制到的目标 *@throwsException */ publicstaticvoidcopyFile(InputStreaminStream,StringnewPath) throwsException{ FileOutputStreamoutStream=null; try{ intbyteread=0; outStream=newFileOutputStream(newPath); byte[]buffer=newbyte[1444]; while((byteread=inStream.read(buffer))!=-1){ outStream.write(buffer,0,byteread); } outStream.flush(); }catch(Exceptione){ throwe; }finally{ if(outStream!=null){ outStream.close(); } if(inStream!=null){ inStream.close(); } } } /** *复制目录 * *@paramoldPath *被复制的目录路径 *@paramnewPath *被复制到的目录路径 *@throwsException */ publicstaticvoidcopyFolder(StringoldPath,StringnewPath) throwsException{ try{ (newFile(newPath)).mkdirs();//假设目录不存在则建立新目录 Filea=newFile(oldPath); String[]file=a.list(); FiletempIn=null; for(inti=0;i以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。