zoukankan      html  css  js  c++  java
  • IO 流(File)

    1.创建文件

    package com.ic.demo01;
    
    import java.io.File;
    import java.io.IOException;
    
    public class FileDemo {
    
        /**
         * @param args
         */
        public static void main(String[] args) throws IOException {
            File file = new File("F://my.txt");
            //此时输出的是将内存中的输入,所以肯定存在
             //System.out.println(file);
            //在磁盘上创建txt文件,用createNewFile时 创建时需要try-catch
            /*if(file.createNewFile()){
                System.out.println("创建成功");
            }else{
                System.out.println("创建失败");
            }*/
            System.out.println(file.getPath());
            // isAbsolute是否是文件
            System.out.println(file.isAbsolute());
            // isDirectory是否是文件夹
            System.out.println(file.isDirectory());
    
        }
    }

    2.目录在F盘中也没有创建成功。只有被创建成功的文件或者目录(文件夹)才判断存在未true

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            File file = new File("F://sxy/my.txt");
            System.out.println(file.isFile());
            System.out.println(file.isDirectory());
            
    
        }

    运行结果:均为false

    3.创建文件目录,之后创建文件(注:删除文件目录时,可以进行迭代处理,判断是否为null)

    package com.ic.demo01;
    
    import java.io.File;
    import java.io.IOException;
    
    public class FileDemo2 {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            File file = new File("F://sxy/my.txt");
            // 先判断文件是否存在
            if (!file.exists()) {
                if (file.getParentFile().mkdirs()) {
                    System.out.println("目录创建成功");
                    try {
                        if (file.createNewFile()) {
                            System.out.println("文件创建成功");
                        } else {
                            System.out.println("文件创建失败");
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("目录创建失败");
                }
    
            }else{
                if(file.exists()){
                    file.delete();
                    System.out.println("文件删除成功");
                }
            }
    
        }
    
    }
  • 相关阅读:
    哈尔滨理工大学软件与微电子学院第八届程序设计竞赛同步赛(低年级)
    ACM_X章求和(数学)
    goj 扫雷(dfs)
    Sereja and Brackets(括号匹配)
    NOIP模拟赛 迷路
    NOIP模拟赛three(3)
    NOIP模拟赛2(two)
    NOIP模拟赛1(one)
    czy的后宫5
    [BZOJ3436]小K的农场
  • 原文地址:https://www.cnblogs.com/sunxiaoyan/p/9195244.html
Copyright © 2011-2022 走看看