Java File操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sicofield/article/details/79963359
import java.io.*;

public class FileTest {

    public static void main(String[] args) {
        testCreateFile();
        testFileConst();
        testFileCreateV2();
        testDeleteFile();
        testCreatePath();
        testListDir();
        testListDirFile();
        testIsDirectory();
        testWalk();
        testWriteRandomAccessFile();
    }
    /**
     * 创建一个空文件
     * File.createFile()
     * python: file = open(path,'w')   file.close()
     *  */
    public static void testCreateFile(){
        File f = new File("D:\\hello.txt");
        try {
            f.createNewFile();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    /**
     * File类的两个常量,separator, pathSeparator
     * */
    public static void testFileConst(){
        System.out.println(File.separator);
        System.out.println(File.pathSeparator);
    }
    /**
     * 要想使得我们的代码跨平台,更加健壮,
     * 所以,采用File.separator, File.pathSeparator
     * */
    public static void testFileCreateV2(){
        String filePath = "D:" + File.separator + "hello.txt";
        File f = new File(filePath);
        try {
            f.createNewFile();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    /**
     * File.delete()
     * python: os.remove(file)
     * */
    public static void testDeleteFile() {
        String fileName = "D:" + File.separator + "hello.txt";
        File f =new File(fileName);
        if(f.exists()){
            if(f.delete()){
                System.out.println("删除成功");
            } else {
                System.out.println("删除失败");
            }
        }else{
            System.out.println("文件不存在");
        }
    }
    /**
     * File.mkdir() 创建单个目录
     * File.mkdirs() 级联创建目录
     * 当然使用mkdirs() 创建单个目录也是可以的
     * python: os.makedirs(path)
     * */
    public static void testCreatePath() {
        String filePath1 = "D:"+ File.separator+"hello1";
        String filePath2 = "D:"+ File.separator+"hello2" + File.separator+"hello3";
        File f = new File(filePath1);
        f.mkdirs();
    }
    /**
     * File.list()返回值为String[] 仅仅是文件名不是全路径
     * python: os.listdir()
     * */
    public static void testListDir() {
        String fileName="D:" + File.separator;
        File f = new File(fileName);
        String[] str = f.list();//对返回的参数要进行检验,否则容易出现NullPointerException
        if(str != null) {
            for (int i = 0; i < str.length; i++) {
                System.out.println(str[i]);
            }
        }
    }
    /**
     * File.listFiles() File[]
     * */
    public static void testListDirFile() {
        String fileName="D:"+ File.separator+"hello1";
        File f = new File(fileName);
        File[] str=f.listFiles();
        if(str != null) {
            for (int i = 0; i < str.length; i++) {
                System.out.println(str[i]);
            }
        }
    }
    /**
    * File.isDirectory()
    * */
    public static void testIsDirectory() {
        String fileName="D:"+File.separator;
        File f=new File(fileName);
        if(f.isDirectory()){
            System.out.println("YES");
        }else{
            System.out.println("NO");
        }
    }
    /**
     * 列写出指定目录下所有文件
     * python: 直接有build-in的walk函数,java需要自己写递归
     * os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
     * for root, dirs, files in os.walk("path", topdown=False):
     *     print(root)
     *     for name in files:
     *         print(os.path.join(root, name))
     *     for name in dirs:
     *         print(os.path.join(root, name))
     * */
    public static void testWalk() {
        String fileName="D:"+File.separator;
        File f=new File(fileName);
        print(f);
    }
    public static void print(File f){
        if(f==null){return;}
        if(f.isDirectory()){
            System.out.println(f);
            File[] fileArray=f.listFiles();
            if(fileArray != null) {
                for(int i = 0; i < fileArray.length; i++) {
                    print(fileArray[i]);
                }
            }
        } else {
            System.out.println(f);
        }
    }
    /**
     * RandomAccessFile写入文件
     * 如果此时打开hello.txt查看的话,会发现那是乱码。
     * 如何解决?
     * */
    public static void testWriteRandomAccessFile(){
        try {
            String fileName = "D:" + File.separator + "hello.txt";
            File f = new File(fileName);
            RandomAccessFile demo = new RandomAccessFile(f, "rw");
            demo.writeBytes("asdsad");
            demo.writeInt(12);
            demo.writeBoolean(true);
            demo.writeChar('A');
            demo.writeFloat(1.21f);
            demo.writeDouble(12.123);
            demo.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页