`
少女杀手
  • 浏览: 130345 次
  • 性别: Icon_minigender_1
  • 来自: 约旦河西岸
社区版块
存档分类
最新评论

JAVA对文件操作

    博客分类:
  • java
阅读更多
package test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.Reader;

/**
*
* @author Administrator
*/
public class FileTest {



/**
     *获取文件夹的创建时间(包括所有文件)
    * @param fileName c://test
     */

   public void creatTime(String fileName){

    File file = new File(fileName);// 文件目录
        try {  
            for (File demoFile : file.listFiles()) {
                Process ls_proc = Runtime.getRuntime().exec(
                        "cmd.exe /c dir " + file.getAbsolutePath() + " /tc");// 通过DOS获得的创建时间
                InputStream is = ls_proc.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String str;
                int i = 0;
                while ((str = br.readLine()) != null) {
                    i++;
                    if (i == 6) {
                        System.out.println("Create time:" + str.substring(0, 17));
                    }
                }
                Date date = new Date(demoFile.lastModified());// 最后修改时间
                System.out.println("Last Time:" + date);
                FileInputStream fis = new FileInputStream(demoFile);
                System.out.println("File Size:" + fis.available());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}



   /**
     *获取文件的创建时间
     * @param fileName c:/fqf.txt
     */

   public void FileCreatTime(String fileName){

     File file = new File(fileName);// 文件目录
        try {  
            Process ls_proc = Runtime.getRuntime().exec(
                        "cmd.exe /c dir " + file.getAbsolutePath() + " /tc");// 通过DOS获得的创建时间
                InputStream is = ls_proc.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                String str;
                int i = 0;
                while ((str = br.readLine()) != null) {
                    i++;
                    if (i == 6) {
                        System.out.println("Create time:" + str.substring(0, 17));
                    }
                }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
     }

  }

    /**
     * 新建目录
     * @param folderPath String 如 c:/fqf
     * @return boolean
     */
    public void newFolder(String folderPath) {
        try {
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            if (!myFilePath.exists()) {
                myFilePath.mkdir();
            }
        } catch (Exception e) {
            System.out.println("新建目录操作出错");
            e.printStackTrace();
        }
    }

    /**
     * 新建文件
     * @param filePathAndName String 文件路径及名称 如c:/fqf.txt
     * @param fileContent String 文件内容
     * @return boolean
     */
    public void newFile(String filePathAndName, String fileContent) {

        try {
            String filePath = filePathAndName;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            if (!myFilePath.exists()) {
                myFilePath.createNewFile();
            }
            FileWriter resultFile = new FileWriter(myFilePath);
            PrintWriter myFile = new PrintWriter(resultFile);
            String strContent = fileContent;
            myFile.println(strContent);
            resultFile.close();

        } catch (Exception e) {
            System.out.println("新建目录操作出错");
            e.printStackTrace();
        }
    }

    /**
     * 删除文件
     * @param filePathAndName String 文件路径及名称 如c:/fqf.txt
     * @param fileContent String
     * @return boolean
     */
    public void delFile(String filePathAndName) {
        try {
            String filePath = filePathAndName;
            filePath = filePath.toString();
            java.io.File myDelFile = new java.io.File(filePath);
            myDelFile.delete();

        } catch (Exception e) {
            System.out.println("删除文件操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 删除文件夹
     * @param filePathAndName String 文件夹路径及名称 如c:/fqf
     * @param fileContent String
     * @return boolean
     */
    public void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); //删除空文件夹

        } catch (Exception e) {
            System.out.println("删除文件夹操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 删除文件夹里面的所有文件
     * @param path String 文件夹路径 如 c:/fqf
     */
    public void delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
            }
        }
    }

    /**
     * 删除文件夹里面的所有文件
     * @param filepath String 文件夹路径 如 c:/fqf
     */
    public void delAll(String filepath) throws IOException {
        File f = new File(filepath);//定义文件路径
        if (f.exists() && f.isDirectory()) {//判断是文件还是目录
            if (f.listFiles().length == 0) {//若目录下没有文件则直接删除
                f.delete();
            } else {//若有则把文件放进数组,并判断是否有下级目录
                File delFile[] = f.listFiles();
                int i = f.listFiles().length;
                for (int j = 0; j < i; j++) {
                    if (delFile[j].isDirectory()) {
                        delAll(delFile[j].getAbsolutePath());//递归调用del方法并取得子目录路径
                    }
                    delFile[j].delete();//删除文件
                }
            }
            delAll(filepath);//递归调用
        }
    }

    /**
     * 复制单个文件
     * @param oldPath String 原文件路径 如:c:/fqf.txt
     * @param newPath String 复制后路径 如:f:/fqf.txt
     * @return boolean
     */
    public 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; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 复制整个文件夹内容
     * @param oldPath String 原文件路径 如:c:/fqf
     * @param newPath String 复制后路径 如:f:/fqf/ff
     * @return boolean
     */
    public void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {//如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }



/**
* 获得 目录    或者 文件夹的大小
* @param f
* @return
* @throws Exception
*/

public long recursionFileList(File f) throws Exception {
  long size = 0;
  File flist[] = f.listFiles();
  for (int i = 0; flist != null && i < flist.length; i++) {
   if (flist[i].isDirectory()) {
    size = size + recursionFileList(flist[i]);
   } else {
    size = size + flist[i].length();
   }
  }
  return size;
}

    /**
     * 移动文件到指定目录
     * @param oldPath String 如:c:/fqf.txt
     * @param newPath String 如:d:/fqf.txt
     */
    public void moveFile(String oldPath, String newPath) {
        copyFile(oldPath, newPath);
        delFile(oldPath);

    }

    /**
     * 移动文件到指定目录
     * @param oldPath String 如:c:/fqf.txt
     * @param newPath String 如:d:/fqf.txt
     */
    public void moveFolder(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);

    }

    /**文件重命名
     * @param path 文件目录
     * @param oldname 原来的文件名
     * @param newname 新文件名
     */
    public void renameFile(String path, String oldname, String newname) {
        {
            if (!oldname.equals(newname)) {
            }
            {//新的文件名和以前文件名不同时,才有必要进行重命名
                File oldfile = new File(path + "/" + oldname);
                File newfile = new File(path + "/" + newname);
                if (newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名
                {
                    System.out.println(newname + "已经存在!");
                } else {
                }
                {
                    oldfile.renameTo(newfile);
                }
            }
        }
    }




1. 当Java.io中,如果文件的操作的时候,判断是否隐藏用File.ishiden()判断是否只读,可用File.canWrite().
2. 当要设置是否是可读或者是隐藏时,在java中除了提供File.setReadOnly()外,就无其他方法了。所以我们必须到Dos环境下去设置,在java中用Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath() + """+ " +R")该方法可以实现。因为路径file.getAbsolutePath()中可能会还有空格,所以必须用引号把它括起来,当作一个参数。这样就可以实现了
(1)   设置只读Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath() + """+ " +R");

(2)   设置可写Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath() + """+ " -R");

(3)   设置隐藏Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath() + """+ " +H");

(4)   设置非隐藏Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath() + """+ " -H"); 1. 当Java.io中,如果文件的操作的时候,判断是否隐藏用File.ishiden()判断是否只读,可用File.canWrite().
2. 当要设置是否是可读或者是隐藏时,在java中除了提供File.setReadOnly()外,就无其他方法了。所以我们必须到Dos环境下去设置,在java中用Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath() + """+ " +R")该方法可以实现。因为路径file.getAbsolutePath()中可能会还有空格,所以必须用引号把它括起来,当作一个参数。这样就可以实现了
(1)   设置只读Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath() + """+ " +R");

(2)   设置可写Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath() + """+ " -R");

(3)   设置隐藏Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath() + """+ " +H");

(4)   设置非隐藏Runtime.getRuntime().exec("attrib " + """ + file.getAbsolutePath() + """+ " -H");
    /**
      * 隐藏文件夹
     * @param fileName
     */
    public void hideFile(String filename) {
        File file = new File(filename);
        // 拼dos命令
        // attrib的祥细功能介绍请在DOS内输入 " attrib /? " 查看
        String sets = "attrib +H \"" + file.getAbsolutePath() + "\"";
        // 输出命令串
        System.out.println(sets);
        // 运行命令串
        try {
            Runtime.getRuntime().exec(sets);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /**
     * 读取字节
     * @param fileName
     */
    public static void readFileByBytes(String fileName) {
        File file = new File(fileName);
        InputStream in = null;
        try {
            System.out.println("以字节为单位读取文件内容,一次读一个字节");
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
                System.out.write(tempbyte);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        try {
            System.out.println("以字节为单位读取文件内容,一次读多个字节");
            byte[] tempbytes = new byte[100];
            int byteread = 0;
            in = new FileInputStream(fileName);
            FileTest.showAvailableBytes(in);
            while ((byteread = in.read(tempbytes)) != -1) {
                System.out.write(tempbytes, 0, byteread);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取字符
     * @param fileName
     */
    public static void readFileByChars(String fileName) {
        File file = new File(fileName);
        Reader reader = null;
        try {
            System.out.println("以字符为单位读取文件内容,一次读一个字符");
            reader = new InputStreamReader(new FileInputStream(file));
             //一次读一个字符
            int tempchar;
            while ((tempchar = reader.read()) != -1) {
                if (((char) tempchar) != '\r') {
                    System.out.print((char) tempchar);
                }
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println("以字符为单位读取文件内容,一次读多个字符");
            reader = new InputStreamReader(new FileInputStream(file));
            char[] tempchars = new char[30];
            //一次读一个字符
            int charread = 0;
            while ((charread = reader.read(tempchars)) != -1) {
                //同样屏蔽掉\r不显示
                if ((charread == tempchars.length) && (tempchars[tempchars.length - 1] != '\r')) {
                    System.out.print(tempchars);
                } else {
                    for (int i = 0; i < charread; i++) {
                        if (tempchars[i] == '\r') {
                            continue;
                        } else {
                            System.out.print(tempchars[i]);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 读取行
     * @param fileName
     */
    public static void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容");
            reader = new BufferedReader(new FileReader(file));
             //一次读一个字符
            String tempString = null;
            int line = 1;
            while ((tempString = reader.readLine()) != null) {
                System.out.println("line " + line + ": " + tempString);
                line++;
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 随机读取
     * @param fileName
     */
    public static void readFileByRandomAccess(String fileName) {
        RandomAccessFile randomFile = null;
        try {
            System.out.println("随机读取一段文件内容");
              //打开一个随机访问文件流,按只读方式
            randomFile = new RandomAccessFile(fileName, "r");
              //文件长度,字节数
            long fileLength = randomFile.length();
              //读文件的起始位置
            int beginIndex = (fileLength > 4) ? 4 : 0;
              //将文件的开始位置移到beginIndex位置
            randomFile.seek(beginIndex);
            byte[] bytes = new byte[10];
            int byteread = 0;
             //一次读10个字节,如果文件内容不足10个字节,则读剩下的字节。
             //将一次读取的字节数赋给byteread
            while ((byteread = randomFile.read(bytes)) != -1) {
                System.out.write(bytes, 0, byteread);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (randomFile != null) {
                try {
                    randomFile.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 通过随机访问追加内容
     * @param fileName
     * @param content
     */
    public static void appendToFileByRandomAccess(String fileName, String content) {
        try {
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            long fileLength = randomFile.length();
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过FileWriter追加内容
     * @param fileName
     * @param content
     */
    public static void appendToFileByFileWriter(String fileName, String content) {
        try {
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void showAvailableBytes(InputStream in) {
        try {
            System.out.println("当前字节输入流中的字节数为" + in.available());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public static void main(String[] args) {

        FileTest file=new FileTest();
        file.newFolder("D://myFile"); //创建问加夹
        file.newFile("D://myFile/test.txt", "你好哦啊啊");//创建文件
        file.copyFile("D://myFile/test.txt", "D://myFile/mytest.txt");//复制文件
        file.copyFolder("D://myFile", "D://File");//复制整个文件夹
        file.delAllFile("D://Test");//删除整个文件夹中的内容
        file.delAll("D://Test");
       long l = file.recursionFileList("C://Program Files/Apache Software Foundation/Tomcat 6.0/webapps/MyZone/zone_picture");
         System.out.println("Total size:"+ (double) ((double) l / 1024 / 1024)+ "M");

                        file.delFolder("D://Test");//删除文件夹
        file.moveFile("D://myFile/test.txt", "D://test.txt");
        file.moveFolder("D://myFile", "C://myFile");
        file.readFileByBytes("D://Test/test.txt");


        file.hideFile("D://Test");
   }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics