总结File类的用法及InputStream、OutputStream的用法

前言

本篇博客,博主将从File类的用法及InputStream、OutputStream的用法几个方面详细介绍,坐好板凳发车啦~~

一.File类

1.1File类概述

Java中通过Java.io.File类来对一个文件(包括目录)进行抽象的描述。注意,有File对象,并不代表真实存在该文件。

我们先来看看File类中的常见属性、构造方法和方法。

属性

修饰符及类型                             属性                                                      说明

static String                        pathSeparator                依赖于系统的路径分隔符,String类型的表示

static char                          pathSeparator                依赖于系统的路径分隔符,char类型的表示

构造方法

签名                                                                                     说明

File(File parent,String child)             根据父目录+孩子文件路径,创建一个新的File实例

File(String pathnam)                        根据文件路径创建一个新的File实例,路径可以是绝对路径

                                                                                             或是相对路径

File(String parent,String child)            根据父目录+孩子文件路径,创建一个新的File实例,

                                                                                         父目录用路径表示

方法

 

1.2示例代码

1.2.1.观察get系列的特点和差异

import java.io.File;
import java.io.IOException;
public class Main {
 public static void main(String[] args) throws IOException {
 File file = new File("..\\hello-world.txt"); // 并不要求该⽂件真实存在
 System.out.println(file.getParent());
 System.out.println(file.getName());
 System.out.println(file.getPath());
 System.out.println(file.getAbsolutePath());
 System.out.println(file.getCanonicalPath());
 }
}


运行结果
..
hello-world.txt
..\hello-world.txt
D:\代码练习\⽂件⽰例1\..\hello-world.txt
D:\代码练习\hello-world.txt

1.2.2.普通文件的创建和删除

import java.io.File;
import java.io.IOException;
public class Main {
 public static void main(String[] args) throws IOException {
 File file = new File("hello-world.txt"); // 要求该⽂件不存在,才能看
 System.out.println(file.exists());
 System.out.println(file.isDirectory());
 System.out.println(file.isFile());
 System.out.println(file.createNewFile());
 System.out.println(file.exists());
 System.out.println(file.isDirectory());
 System.out.println(file.isFile());
 System.out.println(file.createNewFile());
 }
}


运行结果
false
false
false
true
true
false
true
false

删除操作

import java.io.File;
import java.io.IOException;
public class Main {
 public static void main(String[] args) throws IOException {
 File file = new File("some-file.txt"); // 要求该⽂件不存在,才能看到相
 System.out.println(file.exists());
 System.out.println(file.createNewFile());
 System.out.println(file.exists());
 System.out.println(file.delete());
 System.out.println(file.exists());
 }
}



运行结果
false
true
true
true
false

1.2.3.观察deleteExit的现象

import java.io.File;
import java.io.IOException;
public class Main {
 public static void main(String[] args) throws IOException {
 File file = new File("some-file.txt"); // 要求该⽂件不存在,才能看到相
 System.out.println(file.exists());
 System.out.println(file.createNewFile());
 System.out.println(file.exists());
 file.deleteOnExit();
 System.out.println(file.exists());
 }
}



运行结果
false
true
true
true

1.2.4.观察目录的创建

import java.io.File;
import java.io.IOException;
public class Main {
 public static void main(String[] args) throws IOException {
 File dir = new File("some-dir"); // 要求该⽬录不存在,才能看到相同的现
 System.out.println(dir.isDirectory());
 System.out.println(dir.isFile());
 System.out.println(dir.mkdir());
 System.out.println(dir.isDirectory());
 System.out.println(dir.isFile());
 }
}



运行结果
false
false
true
true
false
import java.io.File;
import java.io.IOException;
public class Main {
 public static void main(String[] args) throws IOException {
 File dir = new File("some-parent\\some-dir"); // some-parent 和 so
 System.out.println(dir.isDirectory());
 System.out.println(dir.isFile());
 System.out.println(dir.mkdir());
 System.out.println(dir.isDirectory());
 System.out.println(dir.isFile());
 }
}




运行结果
false
false
false
false
false

注:mkdir() 的时候,如果中间⽬录不存在,则⽆法创建成功; mkdirs() 可以解决这个问题。

import java.io.File;
import java.io.IOException;
public class Main {
 public static void main(String[] args) throws IOException {
 File dir = new File("some-parent\\some-dir"); // some-parent 和 so
 System.out.println(dir.isDirectory());
 System.out.println(dir.isFile());
 System.out.println(dir.mkdirs());
 System.out.println(dir.isDirectory());
 System.out.println(dir.isFile());
 }
}




运行结果
false
false
true
true
false

1.2.5.观察文件重命名

import java.io.File;
import java.io.IOException;
public class Main {
 public static void main(String[] args) throws IOException {
 File file = new File("some-file.txt"); // 要求 some-file.txt 得存在
 File dest = new File("dest.txt"); // 要求 dest.txt 不存在
 System.out.println(file.exists());
 System.out.println(dest.exists());
 System.out.println(file.renameTo(dest));
 System.out.println(file.exists());
 System.out.println(dest.exists());
 }
}





运行结果
true
false
true
false
true

二.InputStream

2.1方法

说明

InputStream 只是⼀个抽象类,要使⽤还需要具体的实现类。关于 InputStream 的实现类有很多,基本可以认为不同的输⼊设备都可以对应⼀个 InputStream 类,我们现在只关⼼从⽂件中读取,所以使⽤ FileInputStream

2.2FileInputStream

 示例代码1:

将⽂件完全读完的两种⽅式。相⽐较⽽⾔,后⼀种的 IO 次数更少,性能更好。
import java.io.*;
// 需要先在项⽬⽬录下准备好⼀个 hello.txt 的⽂件,⾥⾯填充 "Hello" 的内容
public class Main {
 public static void main(String[] args) throws IOException {
 try (InputStream is = new FileInputStream("hello.txt")) {
 while (true) {
 int b = is.read();
 if (b == -1) {
 // 代表⽂件已经全部读完
 break;
 }
 
 System.out.printf("%c", b);
 }
 }
 }
}
import java.io.*;
// 需要先在项⽬⽬录下准备好⼀个 hello.txt 的⽂件,⾥⾯填充 "Hello" 的内容
public class Main {
 public static void main(String[] args) throws IOException {
 try (InputStream is = new FileInputStream("hello.txt")) {
 byte[] buf = new byte[1024];
 int len;
 
 while (true) {
 len = is.read(buf);
 if (len == -1) {
 // 代表⽂件已经全部读完
 break;
 }
 
 for (int i = 0; i < len; i++) {
 System.out.printf("%c", buf[i]);
 }
 }
 }
 }
}

示例代码二:

       这⾥我们把⽂件内容中填充中⽂看看,注意,写中⽂的时候使⽤ UTF-8 编码。hello.txt 中填写 "你好中国"
       注意:这⾥我利⽤了这⼏个中⽂的 UTF-8 编码后⻓度刚好是 3 个字节和⻓度不超过 1024 字节的现状,但这种⽅式并不是通⽤的。
import java.io.*;
// 需要先在项⽬⽬录下准备好⼀个 hello.txt 的⽂件,⾥⾯填充 "你好中国" 的内容
public class Main {
 public static void main(String[] args) throws IOException {
 try (InputStream is = new FileInputStream("hello.txt")) {
 byte[] buf = new byte[1024];
 int len;
 while (true) {
 len = is.read(buf);
 if (len == -1) {
 // 代表⽂件已经全部读完
 break;
 }
 // 每次使⽤ 3 字节进⾏ utf-8 解码,得到中⽂字符
 // 利⽤ String 中的构造⽅法完成
 // 这个⽅法了解下即可,不是通⽤的解决办法
 for (int i = 0; i < len; i += 3) {
 String s = new String(buf, i, 3, "UTF-8");
 System.out.printf("%s", s);
 }
 }
 }
 }
}

2.3利用Scanner进行字符读取

       上述例⼦中,我们看到了对字符类型直接使⽤ InputStream 进⾏读取是⾮常⿇烦且困难的,所以,我们使⽤⼀种我们之前⽐较熟悉的类来完成该⼯作,就是 Scanner 类。

示例代码如下:

import java.io.*;
import java.util.*;
// 需要先在项⽬⽬录下准备好⼀个 hello.txt 的⽂件,⾥⾯填充 "你好中国" 的内容
public class Main {
 public static void main(String[] args) throws IOException {
 try (InputStream is = new FileInputStream("hello.txt")) {
 try (Scanner scanner = new Scanner(is, "UTF-8")) {
 while (scanner.hasNext()) {
 String s = scanner.next();
 System.out.print(s);
 }
 }
 }
 }
}

三.OutputStream

3.1方法

说明:

OutputStream 同样只是⼀个抽象类,要使⽤还需要具体的实现类。我们现在还是只关⼼写⼊⽂件
中,所以使⽤ FileOutputStream

3.2FileOutputStream

五个示例代码如下:

import java.io.*;
public class Main {
 public static void main(String[] args) throws IOException {
 try (OutputStream os = new FileOutputStream("output.txt")) {
 os.write('H');
 os.write('e');
 os.write('l');
 os.write('l');
 os.write('o');
 // 不要忘记 flush
 os.flush();
 }
 }
}
import java.io.*;
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'
 };
 os.write(b);
 
 // 不要忘记 flush
 os.flush();
 }
 }
}
import java.io.*;
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'
 };
 os.write(b, 0, 4);
 
 // 不要忘记 flush
 os.flush();
 }
 }
}
import java.io.*;
public class Main {
 public static void main(String[] args) throws IOException {
 try (OutputStream os = new FileOutputStream("output.txt")) {
 String s = "Nothing";
 byte[] b = s.getBytes();
 os.write(b);
 
 // 不要忘记 flush
 os.flush();
 }
 }
}
import java.io.*;
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();
 }
 }
}

3.3利用PrintWriter找到我们熟系的方法

上述,我们其实已经完成输出⼯作,但总是有所不⽅便,我们接来下将 OutputStream 处理下,使⽤PrintWriter 类来完成输出,因为PrintWriter 类中提供了我们熟悉的 print/println/printf ⽅法。
示例代码如下:
OutputStream os = ...;
OutputStreamWriter osWriter = new OutputStreamWriter(os, "utf-8"); 
PrintWriter writer = new PrintWriter(osWriter);
// 接下来我们就可以⽅便的使⽤ writer 提供的各种⽅法了
writer.print("Hello");
writer.println("你好");
writer.printf("%d: %s\n", 1, "没什么");
// 不要忘记 flush
writer.flush();
import java.io.*;
public class Main {
 public static void main(String[] args) throws IOException {
 try (OutputStream os = new FileOutputStream("output.txt")) {
 try (OutputStreamWriter osWriter = new OutputStreamWriter(os, "UTF-8
 try (PrintWriter writer = new PrintWriter(osWriter)) {
 writer.println("我是第⼀⾏");
 writer.print("我的第⼆⾏\r\n");
 writer.printf("%d: 我的第三⾏\r\n", 1 + 1);
 writer.flush();
 }
 }
 }
 }
}

尾语

这篇博客到这里就结束啦,希望可以给大家带来帮助~~

相关推荐

  1. 总结 Thread 基本

    2024-03-12 06:40:03       26 阅读
  2. 【C++STL】String函数用法总结

    2024-03-12 06:40:03       34 阅读
  3. File方法

    2024-03-12 06:40:03       37 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-12 06:40:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-12 06:40:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-12 06:40:03       82 阅读
  4. Python语言-面向对象

    2024-03-12 06:40:03       91 阅读

热门阅读

  1. 【IVA】什么是IVA?

    2024-03-12 06:40:03       49 阅读
  2. 块级作用域、变量提升

    2024-03-12 06:40:03       39 阅读
  3. 列表循环多个el-form-item并校验

    2024-03-12 06:40:03       41 阅读
  4. PYTHON 120道题目详解(100-102)

    2024-03-12 06:40:03       47 阅读
  5. Golang-如何优雅的关闭一个Channel?

    2024-03-12 06:40:03       39 阅读
  6. Windows版Redis启用密码

    2024-03-12 06:40:03       38 阅读
  7. 正则表达式笔记+demo

    2024-03-12 06:40:03       45 阅读
  8. Leetcode 第388场周赛 问题和解法

    2024-03-12 06:40:03       45 阅读
  9. 商品上传上货搬家使用1688商品采集api接口

    2024-03-12 06:40:03       40 阅读
  10. JsonUtility和LitJson的特点与区别

    2024-03-12 06:40:03       41 阅读