总结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();
 }
 }
 }
 }
}

尾语

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

  • 23
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值