`
zengshaotao
  • 浏览: 760502 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

java 文件操作

    博客分类:
  • java
 
阅读更多
public class FileOperate {
 //新建目录
 public void newFolder(String folderPath) {
 try {
  File myFilePath = new File(folderPath);
 if (!myFilePath.exists()) {
        myFilePath.mkdir();
    }
 }
 catch (Exception e) {
 System.out.println("新建目录操作出错");
 e.printStackTrace();
 }
 }

       //新建文件
 public void newFile(String filePath) {
 try {
 File myFilePath = new File(filePath);
 if (!myFilePath.exists()) {
 myFilePath.createNewFile();
 }catch (Exception e) {
 System.out.println("新建文件操作出错");
 e.printStackTrace();
 }
 }

       //删除文件
 public void delFile(String filePath) {
 try {
 File myDelFile = new File(filePath);
       myDelFile.delete();
 }
 catch (Exception e) {
 System.out.println("删除文件操作出错");
 e.printStackTrace();
 }
 }

       //删除文件夹,需要文件夹是空的
 public void delFolder(String folderPath) {
 try {
 delAllFile(folderPath);
 File myFilePath = new File(folderPath);
 myFilePath.delete(); //删除空文件夹
 }
 catch (Exception e) {
 System.out.println("删除文件夹操作出错");
 e.printStackTrace();
 }
 }

       //删除文件夹所有的内容
 public void delAllFile(String path) {
 File file = new File(path);
 if (!file.exists()) {
 return;
 }
 if (!file.isDirectory()) {
 return;
 }
 String[] objList = file.list();
 File temp = null;
 for (int i = 0; i < objList.length; i++) {
 if (path.endsWith(File.separator)) {
 temp = new File(path + objList[i]);
 }
 else {
 temp = new File(path + File.separator + objList[i]);
 }
 if (temp.isFile()) {
 temp.delete();
 }
 if (temp.isDirectory()) {
 delAllFile(path+"/"+ objList[i]);//先删除文件夹里面的文件
 delFolder(path+"/"+ objList[i]);//再删除空文件夹
 }
 }
 }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics