栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

文件操作和IO

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

文件操作和IO

目录

1. Java中操作文件

1.1 File 常用构造方法

1.2 常用方法

2. 文件内容的读写 --- 数据流

2.1 InputStream: 输入流

2.1.1 InputStream 常用方法

2.1.2 FileInputStream

2.1.3 使用Scanner 进⾏数据读取

2.2 OutputStream:输出流

2.2.1 OutputStream 常⽤⽅法

2.2.2 实现数据写⼊  

 2.2.3 使⽤ PrintWriter 进⾏写⼊


1. Java中操作文件

1.1 File 常用构造方法

public class FileDemo1 {
    public static void main(String[] args) {
        // 构造⽅法 1: 根据⽗⽬录 + 孩⼦⽂件路径,创建⼀个新的 File 实例
        File pfile = new File("d:\");
        File file = new File(pfile,"a.txt");
        System.out.println("文件1路径" +file.getPath());
        //构造⽅法 2: 根据⽂件路径创建⼀个新的 File 实例,路径可以 是绝对路径或者相对路径 (常用)
        File file2 = new File("d:\b.txt");
        System.out.println("文件2路径" + file2.getPath());
        //构造⽅法 3: 根据⽗⽬录 + 孩⼦⽂件路径,创建⼀个新的 File 实例,⽗⽬录⽤路径表示
        File file3 = new File("d:\","c.txt");
        System.out.println("文件3路径" + file3.getPath());
    }
}
输出:
文件1路径d:a.txt
文件2路径d:b.txt
文件3路径d:c.txt

1.2 常用方法

  

 getPath() VS getAbsolutePath() VS getCanonicalPath() :

public class FileDemo2 {
    public static void main(String[] args) throws IOException {
        File file = new File("../a.txt");  // .. 表示返回上一层目录
        System.out.println("文件名称:" + file.getName());
        System.out.println("文件目录(getPath)(相对路径):" + file.getPath());
        System.out.println("文件绝对路径:" + file.getAbsolutePath());
        System.out.println("文件标准路径:" + file.getCanonicalPath()); //最靠谱的方式
    }
}
输出:
文件名称:a.txt
文件目录(getPath)(相对路径):..a.txt
文件绝对路径:D:appsJavamavenio-demo..a.txt
文件标准路径:D:appsJavamavena.txt
public class FileDemo3 {
    public static void main(String[] args) throws IOException {
        File file = new File("a.txt");
        System.out.println("文件是否存在:" + file.exists());
        System.out.println("是否为文件夹:" + file.isDirectory());
        System.out.println("是否为文件:" + file.isFile());
        System.out.println();
        boolean result = file.createNewFile(); // 创建文件
        System.out.println("文件创建:" + result);
        System.out.println("文件是否存在:" + file.exists());
        System.out.println("是否为文件夹:" + file.isDirectory());
        System.out.println("是否为文件:" + file.isFile());
    }
}
输出:
文件是否存在:false
是否为文件夹:false
是否为文件:false

文件创建:true
文件是否存在:true
是否为文件夹:false
是否为文件:true
        File file2 = new File("c");
        if (!file2.exists()) { // 文件不存在,创建文件
            System.out.println("创建文件:" + file2.createNewFile());
        }
        System.out.println("是否为文件夹:" + file2.isDirectory());
        System.out.println("是否为文件:" + file2.isFile());

输出:
创建文件:true
是否为文件夹:false
是否为文件:true

 delete 和 deleteOnExit  :

public class FileDemo4 {
    public static void main(String[] args) throws IOException {
        // 先得的一个 file 对象
        File file = new File("a.txt");
        // 判断 file 对象是否存在
        if (file.exists()) {
            // 如果存在则删除文件
            boolean result = file.delete();
            System.out.println("文件删除:" + result);
        } else {
            // 如果不存在的创建文件
            boolean reuslt = file.createNewFile();
            System.out.println("新建文件:" + reuslt);
        }
    }
}
输出:
文件删除:true
public class FileDemo5 {
    public static void main(String[] args) throws IOException, InterruptedException {
        File file = new File("a.txt");
        if (!file.exists()) {
            // 如果不存在,则新建
            System.out.println("新建文件:" + file.createNewFile());
        }
        // 删除文件
        System.out.println("开始删除文件");
        file.deleteOnExit();
        Thread.sleep(5 * 1000);
    }
}

 delete 和 deleteOnExit 区别 :

第一个区别:有无返回值

 

 第二个区别 :delete 在退出程序(删除的相关程序)途中会被删除,deleteOnExit 不会被删除。

第三个区别:deleteOnExit 在程序运⾏结束后,⽂件被删除,但如果是⼈为退出程序,⽂件不会被删除。

创建文件夹
public class FileDemo6 {
    public static void main(String[] args) {
        File file = new File("mytest/apps");
        System.out.println("是否为文件夹:" + file.isDirectory());
        System.out.println("是否为文件:" + file.isFile());
        System.out.println();
//        boolean result = file.mkdir(); // 创建一个文件夹
        boolean result = file.mkdirs(); // 创建多级文件夹
        System.out.println("创建文件夹:" + result);
        System.out.println("是否为文件夹:" + file.isDirectory());
        System.out.println("是否为文件:" + file.isFile());
    }
}
文件重命名
public class FileDemo7 {
    public static void main(String[] args) throws IOException {
        // 将 a.txt -> 重命名 b.txt
        File file = new File("b.txt");
        File tarFile = new File("c.txt");
        if (!file.exists()) {
            // 先创建文件
            file.createNewFile();
        }
        // 重命名文件
        boolean result = file.renameTo(tarFile);
        System.out.println("重命名结果:" + result);
    }
}

2. 文件内容的读写 --- 数据流

2.1 InputStream: 输入流 InputStream 输⼊流是⽤来读取数据的 。 

2.1.1 InputStream 常用方法

2.1.2 FileInputStream

由于 InputStream 是一个抽象类,因此,对文件进行操作时,使用FileInputStream

 读取方法1:read() 方法读取文件:

public class InputStreamDemo1 {
    public static void main(String[] args) throws IOException, InterruptedException {
        // 1.创建流对象
        // 2.读写操作
        // 3.关闭流

        // 1.创建流对象
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("c.txt");
            // 2.读写操作
            while (true) {
                int c = inputStream.read();
                // 如果流返回的 -1,说明数据已经读取完了
                if (c == -1) break;
                Thread.sleep(200);
                System.out.printf("%c", c);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 3.关闭流
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

上述代码可以优化为;

public class InputStreamDemo2 {
    public static void main(String[] args) {
        // 1.创建流对象  try-catch-resource(JDK 1.7)   ---  不需要关闭资源
        try (InputStream inputStream = new FileInputStream("c.txt")) {
            // 2.读写操作
            while (true) {
                int c = inputStream.read();
                // 如果流返回的 -1,说明数据已经读取完了
                if (c == -1) break;
                Thread.sleep(200);
                System.out.printf("%c", c);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 读取方法2:read ( byte[ ] b ) 方法来读取文件:

public class InputStreamDemo3 {
    public static void main(java.lang.String[] args) {
        try (InputStream inputStream = new FileInputStream("c.txt")) {
            byte[] bytes = new byte[1024];
            while (true) { // 如果数据超过了 byte 容量,会读取多次
                int c = inputStream.read(bytes);
                if (c == -1) break;
                System.out.println(new String(bytes, "utf-8"));
                Thread.sleep(200);
            }
        } catch (Exception e) {
        }
    }
}

2.1.3 使用Scanner 进⾏数据读取

public class InputStreamDemo4 {
    public static void main(String[] args) {
        try (FileInputStream inputStream = new FileInputStream("c.txt")) {
            try (Scanner scanner = new Scanner(inputStream, "utf8")) {
                while (scanner.hasNext()) {
                    System.out.println(scanner.nextLine());
                }
            }
        } catch (Exception e) {
        }

    }
}

2.2 OutputStream:输出流

OutputStream 输出流是进⾏数据写⼊的。 

2.2.1 OutputStream 常⽤⽅法

2.2.2 实现数据写⼊  

 由于 OutputStream是一个抽象类,因此,对文件进行操作时,使用FileOutputStream 。

 写入操作,每次写入一个字符:

public class OutputStreamDemo1 {
    public static void main(String[] args) throws IOException {
        File file = new File("mytest.txt");
        if (!file.exists()) {
            // 新建文件
            System.out.println("新建文件:" + file.createNewFile());
        }
        // 文件写入操作
        try (OutputStream outputStream = new FileOutputStream(file)) {
            outputStream.write('H');
            outputStream.write('e');
            outputStream.write('l');
            outputStream.write('l');
            outputStream.write('o');
            outputStream.flush();
        }
    }
}
字节数组批量写⼊:
public class OutputStreamDemo2 {
    public static void main(String[] args) throws IOException {
        File file = new File("mytest.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        // 写入操作
        try (OutputStream outputStream = new FileOutputStream(file)) {
            byte[] bytes = new byte[]{
                    'H', 'i'
            };
            outputStream.write(bytes);
            outputStream.flush();
        }

    }
}
写⼊部分数据:
public class Main {
    public static void main(String[] args) throws IOException {
        try (OutputStream os = new FileOutputStream("output.txt")) {
            byte[] b = new byte[] {
               (byte)'G', (byte)'o', (byte)'o', (byte)'d', (byte)'B', (byte)'a', (byte)'d'
           };
            os.write(b, 0, 4);
            // 不要忘记 flush
            os.flush();
       }
   }
}
字符串写⼊:

public class Main {
    public static void main(String[] args) throws IOException {
        try (OutputStream os = new FileOutputStream("output.txt")) {
            String s = "你好中国";
            byte[] b = s.getBytes("utf-8");
         os.write(b);
            // 不要忘记 flush
            os.flush();
       }
   }
}

 2.2.3 使⽤ PrintWriter 进⾏写⼊
public class OutputStreamDemo3 {
    public static void main(String[] args) throws IOException {
        File file = new File("mytest.txt");
        if (!file.exists()) file.createNewFile();
        try (PrintWriter printWriter = new PrintWriter(file)) {
            printWriter.println("这是第一行数据");
            printWriter.println("这是第二行数据:");
            printWriter.printf("我叫:%s,今年:%d,至今未婚。",
                    "张三", 18);
            printWriter.flush();
        }
    }
}

 

但是上述代码是将原文件中的数据直接覆盖掉,如果进行数据追加:

public class OutputStreamDemo4 {
    public static void main(String[] args) throws IOException {
        File file = new File("mytest.txt");
        if (!file.exists()) file.createNewFile();

        // 数据追加
        try (FileWriter fileWriter = new FileWriter(file, true)) {
            fileWriter.append("n我是追加的数据III");
            fileWriter.flush();
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937225.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号