Java的IO流
1.简单介绍
2.常用IO流:
3.分类
-
接下来所有的内容都是
InputStream
、OutputStream
、Reader
、Writer
的子类。 -
和
File
相关的IO流
有四个分别是FileInputStream
和FileOutputStream
,FileReader
和FileWriter
。其中FileReader
和FileWriter
为字符IO流。FileInputStream
和FileOutputStream
为字节IO流。 -
缓冲流相关的有四个
BufferedInputStream
、BufferedOutputStream
、BufferedReader
、BufferedWriter
。 -
转换流相关的:
InputStreamReader
和OutputStreamWriter
。 -
打印流相关的:
PrintStream
和PrintWriter
-
对象相关的:
ObjectInputStream
和ObjectOutputStream
-
数据相关的:
DataInputStream
和DataOutputStream
-
字节数组相关的:
ByteArrayInputStream
和ByteArrayOutputStream
-
压缩和解压缩相关的:
GZIPInputStream
和GZIPOutputStream
-
线程相关的:
PipedInputStream
和PipedOutputStream
4.IO具体用法举例:
4.1文件字节输入流--FileInputStream
package com.powernode;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamtest2 {
public static void main(String[] args) {
// 声明一个FileInputStream对象
FileInputStream fis = null;
try {
// 声明一个int型变量,用于存储读取到的数据
int readbyte;
// 创建FileInputStream对象,以读取文件
fis = new FileInputStream("D:/project/IOStream/src/main/resources/FileInputStreamtest1.txt");
// 当读取到的数据不为-1时,循环读取
while((readbyte=fis.read())!=-1){
// 将读取到的数据输出
System.out.print(readbyte+" ");
}
}catch (IOException e) {
// 打印异常信息
e.printStackTrace();
}finally {
// 当FileInputStream对象不为空时,关闭流
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
// 抛出异常
throw new RuntimeException(e);
}
}
}
}
}
4.2文件字节输出流--FileOutputStream
package com.powernode;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class FileOutputStreamtest1 {
public static void main(String[] args) {
// 创建一个输出流对象
OutputStream os = null;
try {
// 创建一个文件输出流对象,参数为文件路径
os = new FileOutputStream("D:\\project\\IOStream\\src\\main\\resources\\FileOutputStreamTest1.txt");
// 将字符串写入文件
os.write("写入成功".getBytes());
// 刷新输出流
os.flush();
} catch (IOException e) {
// 捕获异常并打印堆栈信息
e.printStackTrace();
} finally {
// 关闭输出流
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
// 捕获异常并抛出运行时异常
throw new RuntimeException(e);
}
}
}
}
4.3通过FileInputStream和FileOutputSteam进行文件复制
package com.powernode;
import java.io.*;
public class CopyByInputStreamAndOutputStream {
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
try {
// 创建输入流,读取文件
in = new FileInputStream("D:\\project\\IOStream\\src\\main\\resources\\FileInputStreamtest1.txt");
// 创建输出流,写入文件
out = new FileOutputStream("D:\\project\\IOStream\\src\\main\\resources\\FileOutputStreamCopyTest1.txt");
int readCount = 0;
byte[] buffer = new byte[1024];
// 循环读取文件内容,直到文件末尾
while ((readCount = in.read(buffer)) != -1) {
// 将读取的内容写入文件
out.write(buffer, 0, readCount);
}
// 刷新输出流,确保所有数据都写入文件
out.flush();
} catch (IOException e) {
// 捕获IO异常,并打印异常信息
e.printStackTrace();
} finally {
try {
// 关闭输入流
if (in != null) {
in.close();
}
// 关闭输出流
if (out != null) {
out.close();
}
} catch (IOException E) {
// 捕获IO异常,并打印异常信息
E.printStackTrace();
}
}
}
}
4.4 try-with-resources
资源自动关闭,凡是实现AutoCloseable
接口的流都可以实现自动关闭,java7新特性。
package com.powernode;
import java.io.*;
public class TryWithResources {
public static void main(String[] args) {
// 创建一个输入流,用于读取文件
try (InputStream in = new FileInputStream("D:\\project\\IOStream\\src\\main\\resources\\FileInputStreamtest1.txt");
// 创建一个输出流,用于写入文件
OutputStream out = new FileOutputStream("D:\\project\\IOStream\\src\\main\\resources\\TryWithResource.txt");
) {
// 定义一个计数器,用于记录读取的字节数
int readCount = 0;
// 定义一个字节数组,用于存储读取的数据
byte[] buffer = new byte[1024];
// 使用循环读取文件内容
while ((readCount = in.read(buffer)) != -1) {
// 将读取的数据写入输出流
out.write(buffer, 0, readCount);
}
// 刷新输出流,确保所有数据被写入文件
out.flush();
} catch (IOException e) {
// 打印异常信息
e.printStackTrace();
}
}
}
4.5 文件字符--输入流FileReader
package com.powernode;
import java.io.FileReader;
import java.io.IOException;
/**
* 测试FileReader读取文件内容
*/
public class FileReaderTest01 {
public static void main(String[] args) {
// 使用try-with-resources语句,确保FileReader在结束时自动关闭
try(FileReader fileReader = new FileReader("D:\\project\\IOStream\\src\\main\\resources\\FileReadTest.txt")) {
// 创建一个字符数组,用于存储读取的数据
char[] buf = new char[1024];
// 定义一个整数,用于存储每次读取的字节数
int len;
// 循环读取文件内容,直到读取到-1为止
while((len=fileReader.read(buf))!=-1){
// 将读取到的字符输出到控制台
System.out.print(new String(buf,0,len));
}
}catch (IOException e) {
// 打印异常信息
e.printStackTrace();
}
}
}
4.6文件字符输出流--FileWriter
package com.powernode;
import java.io.FileWriter;
public class FileWriterTest1 {
public static void main(String[] args) {
// 创建一个FileWriter对象,用于写入文件
try (FileWriter fileWriter = new FileWriter("D:\\project\\IOStream\\src\\main\\resources\\FileWritertest.txt",true);){
// 写入字符串
fileWriter.write("Hello World");
fileWriter.write("you can do it ");
// 刷新缓冲区,确保数据被写入磁盘
fileWriter.flush();
} catch (Exception e) {
// 打印异常堆栈信息
e.printStackTrace();
}
}
}
4.7 使用FileReader和FileWriter拷贝普通文本文件
package com.powernode;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FileReaderAndFileWriterCopy {
public static void main(String[] args) {
try(FileReader fileReader = new FileReader("D:\\project\\IOStream\\src\\main\\resources\\FileWriter.txt");
FileWriter fileWriter = new FileWriter("D:\\project\\IOStream\\src\\main\\resources\\FileWriterAndFileReaderCopy.txt")
){
// 定义一个变量,用于记录读取的字节数
int readCount = 0;
// 定义一个字符数组,用于存储读取的数据
char[] buffer = new char[1024];
// 使用循环读取文件内容,并写入到新的文件中
while((readCount=fileReader.read(buffer) )!= -1){
fileWriter.write(buffer, 0, readCount);
}
}catch (IOException E){
E.printStackTrace();
}
}
}
4.8关于文件的路径的理解:
我们之前的演示都是使用绝对路径,实际上我们也可以使用相对路径。对于相对路径来说什么是最重要的呢?在IDEA工具中,默认的当前路径是 project 的根。(项目的根就是当前路径)
package com.powernode;
import java.io.FileReader;
import java.io.IOException;
public class AboutFilePath {
public static void main(String[] args) {
// 创建两个FileReader对象,分别读取两个文件
try(FileReader in = new FileReader("log.txt");
FileReader in1 =new FileReader("./src/main/resources/AboutFilePath.txt");
){
// 定义一个计数器
int Count =0;
// 定义一个字符数组,用于存储读取的字符
char[] c = new char[50];
// 循环读取文件中的字符
while((Count = in1.read(c))!=-1){
// 将读取的字符转换为字符串并输出
System.out.println(new String(c,0,Count));
}
}catch (IOException e){
// 捕获异常并打印异常信息
e.printStackTrace();
}
}
}
4.9缓冲流:
BufferedInputStream、BufferedOutputStream(适合读写非普通文本文件)
BufferedReader、BufferedWriter(适合读写普通文本文件。)
缓冲流的读写速度快,原理是:在内存中准备了一个缓存。读的时候从缓存中读。写的时候将缓存中的数据一次写出。都是在减少和磁盘的交互次数。如何理解缓冲区?家里盖房子,有一堆砖头要搬在工地100米外,单字节的读取就好比你一个人每次搬一块砖头,从堆砖头的地方搬到工地,这样肯定效率低下。然而聪明的人类会用小推车,每次先搬砖头搬到小车上,再利用小推车运到工地上去,这样你再从小推车上取砖头是不是方便多了呀!这样效率就会大大提高,缓冲流就好比我们的小推车,给数据暂时提供一个可存放的空间。
缓冲流都是处理流/包装流。FileInputStream/FileOutputStream是节点流。
关闭流只需要关闭最外层的处理流即可,通过源码就可以看到,当关闭处理流时,底层节点流也会关闭。
输出效率是如何提高的?在缓冲区中先将字符数据存储起来,当缓冲区达到一定大小或者需要刷新缓冲区时,再将数据一次性输出到目标设备。
输入效率是如何提高的? read()方法从缓冲区中读取数据。当缓冲区中的数据不足时,它会自动从底层输入流中读取一定大小的数据,并将数据存储到缓冲区中。大部分情况下,我们调用read()方法时,都是从缓冲区中读取,而不需要和硬盘交互。
可以编写拷贝的程序测试一下缓冲流的效率是否提高了!
缓冲流的特有方法(输入流):以下两个方法的作用是允许我们在读取数据流时回退到原来的位置(重复读取数据时用)
void mark(int readAheadLimit); 标记位置(在Java21版本中,参数无意义。低版本JDK中参数表示在标记处最多可以读取的字符数量,如果你读取的字符数超出的上限值,则调用reset()方法时出现IOException。)
void reset(); 重新回到上一次标记的位置
这两个方法有先后顺序:先mark再reset,另外这两个方法不是在所有流中都能用。有些流中有这个方法,但是不能用。
4.10 BufferedInputSteam
package com.powernode;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class BufferedInputStreamTest1 {
public static void main(String[] args) {
// 创建一个BufferedInputStream对象,用于读取文件
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("D:\\project\\IOStream\\src\\main\\resources\\BufferedInputStream.txt"))) {
int len ;
// 创建一个字节数组,用于存储读取到的数据
byte[] bytes = new byte[1024];
// 循环读取文件内容
while ((len = bufferedInputStream.read(bytes)) != -1) {
// 将字节数组转换为字符串并输出
System.out.println(new String(bytes, 0, len));
}
} catch (IOException e) {
// 捕获异常并打印异常信息
e.printStackTrace();
}
}
}
4.11 BufferedOutputStream
package com.powernode;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferedOutputStreamTest {
public static void main(String Args[]){
// 创建一个BufferedOutputStream对象,用于将数据写入文件
try(BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("D:\\project\\IOStream\\src\\main\\resources\\BufferedOutputStream.txt"))){
// 将字符串转换为字节数组,并写入文件
bufferedOutputStream.write("床前明月光".getBytes());
// 刷新缓冲区,将数据写入文件
bufferedOutputStream.flush();
}catch (IOException e){
// 捕获异常并打印堆栈信息
e.printStackTrace();
}
}
}
4.12 BufferedReader
package com.powernode;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderTest2 {
public static void main(String[] args) {
try(BufferedReader bufferedReader = new BufferedReader(new FileReader("log.txt"))) {
// 创建一个BufferedReader对象,用于读取文件log.txt
int count =0;
String linecontent;
// 使用while循环逐行读取文件内容
while((linecontent=bufferedReader.readLine())!=null){
// 打印每行内容
System.out.println(linecontent);
}
}catch (IOException e){
e.printStackTrace();
}
}
}
package com.powernode;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderTest1 {
public static void main(String[] args) {
// 使用try-with-resources语句创建一个BufferedReader对象,用于读取文件
try(BufferedReader bufferedReader = new BufferedReader(new FileReader("log.txt"))) {
int count =0;
char[] chars = new char[1024];
// 使用while循环读取文件中的内容
while((count=bufferedReader.read(chars))!=-1){
// 将读取到的内容转换为字符串并打印
System.out.println(new String(chars,0,count));
}
}catch (IOException e){
e.printStackTrace();
}
}
}
4.13 BufferedWriter
package com.powernode;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterTest {
public static void main(String Args[]){
try (BufferedWriter bf = new BufferedWriter(new FileWriter("log.txt",true))){
// 创建一个新的BufferedWriter对象,并将其写入到文件log.txt中
bf.newLine();
// 写入一个新行
bf.write("唐代李白");
// 写入字符串“唐代李白”
}catch (IOException e){
e.printStackTrace();
// 捕获并打印异常
}
}
}
4.14 mark和reset
package com.powernode;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
// 缓冲输入流特有 BufferedReader BufferedInputStream
public class MarkAndResetTest1 {
public static void main(String Args[]) {
try (BufferedReader bf = new BufferedReader(new FileReader("MarkAndResetTest.txt"))) {
// 读取文件中的第一个字符
System.out.println(bf.read());
// 读取文件中的第二个字符
System.out.println(bf.read());
// 在文件中的第三个字符处设置标记
bf.mark(2);
// 读取文件中的第四个字符
System.out.println(bf.read());
// 读取文件中的第五个字符
System.out.println(bf.read());
// 将文件指针重置到标记的位置
bf.reset();
// 读取文件中的第六个字符
System.out.println(bf.read());
// 读取文件中的第七个字符
System.out.println(bf.read());
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.15 FileReader 乱码问题
创建FileReader
的时候如果没有指定,解码字符集,那么系统会默认使用UTF-8
字符集进行解码。所以如果读取文件为UTF-8
的文件那么自然没有问题。但是如果我们读取ANSI
编码文件,但是不指定解码字符集,那么就会发生乱码。
4.16 FileWriter乱码问题
使用 FileWriter
进行编码的时候,如果idea的编码格式是UTF-8
,但是文件的编码方式是gbk
这个时候如果直接写入就会造成乱码。
4.17 InputStreamReader
package com.powernode;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class InputStreamReaderTest {
public static void main(String Args[]){
// 创建一个InputStreamReader对象,用于读取文件
try(InputStreamReader ir = new FileReader("log.txt", Charset.forName("GBK"))){
int count ;
// 创建一个字符数组,用于存储读取的字符
char[] c = new char[1024];
// 循环读取文件中的字符
while((count=ir.read(c))!=-1){
// 将读取的字符转换为字符串并输出
System.out.println(new String(c,0,count));
}
}catch (IOException e){
// 捕获异常并打印异常信息
e.printStackTrace();
}
}
}
由于InputStreamReader
是FileReader
的父类,所以刚才的代码我们也可以这样写:
package com.powernode;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
public class FileReaderTest2 {
public static void main(String[] args) {
// 使用try-with-resources语句,自动关闭FileReader对象
try (FileReader fr = new FileReader("log.txt", Charset.forName("GBK"));) {
// 定义一个变量count,用于存储每次读取的字符数
int count;
// 定义一个字符数组c,用于存储每次读取的字符
char[] c = new char[1024];
// 使用while循环,循环读取文件中的字符
while((count=fr.read(c))!=-1){
// 将读取的字符转换为字符串,并输出
System.out.println(new String(c,0,count));
}
} catch (IOException e) {
// 捕获异常,并打印异常信息
e.printStackTrace();
}
}
}
由于原来的文件是utf-8
编码格式,但是现在我才用GBK
读取,所以出现乱码:
4.18 OutStreamWriter解决乱码问题:
* OutputStreamWriter是一个编码的过程。
* 如果OutputStreamWriter在编码的过程中使用的字符集和文件的字符集不一致时会出现乱码。
*
* FileWriter是OutputStreamWriter的子类。
* FileWriter的出现简化了java代码。
* FileWriter是一个包装流,不是节点流。
*/
public class OutputStreamWriterEncodingTest {
public static void main(String[] args) throws Exception{
FileWriter osw = new FileWriter("E:\\powernode\\02-JavaSE\\code\\file4.txt", Charset.forName("UTF-8"), true);
// 开始写
osw.write("来动力节点学Java");
osw.flush();;
osw.close();
}
}
4.19 数据流 DataInputStream DataOutputStream
DataOutputStream:
package com.powernode;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataOutputStreamTest {
public static void main(String[] args) throws IOException {
// 创建DataOutputStream对象,用于向文件中写入数据
DataOutputStream ds = new DataOutputStream(new FileOutputStream("D:\\project\\IOStream\\src\\main\\resources\\data"));
// 定义要写入的数据
String data = "hello dataoutputstream";
// 使用writeUTF方法将数据写入文件
ds.writeUTF(data);
// 刷新缓冲区,确保数据被写入文件
ds.flush();
// 关闭DataOutputStream对象
ds.close();
}
}
DataInputStream:
package com.powernode;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class DataInputStreamTest {
public static void main(String[] args) throws IOException {
// 创建一个DataInputStream对象,用于读取文件
DataInputStream di = new DataInputStream(new FileInputStream("D:\\project\\IOStream\\src\\main\\resources\\data"));
// 读取UTF格式的字符串
String data1 =di.readUTF();
// 输出读取的字符串
System.out.println(data1);
}
}
输出结果:
4.20 序列化与反序列化 ObjectInputStream 和 ObjectOuputStream
ObjectOutputStream:
package com.powernode;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
public class ObjectOutputStreamTest {
public static void main(String[] args) throws IOException {
// 创建一个ObjectOutputStream对象,用于将对象写入文件
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("objectTest"));
// 创建一个Date对象
Date data = new Date();
System.out.println(data);
// 将Date对象写入文件
oos.writeObject(data);
// 刷新缓冲区,确保数据被写入文件
oos.flush();
// 关闭ObjectOutputStream对象
oos.close();
}
}
ObjectInputStream:
package com.powernode;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Date;
public class ObjectInputStreamTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// 创建一个ObjectInputStream对象,用于读取文件中的对象
ObjectInputStream oi = new ObjectInputStream(new FileInputStream("objectTest"));
// 从文件中读取一个Date对象
Date date = (Date)(oi.readObject());
// 输出读取到的Date对象
System.out.println(date);
// 关闭ObjectInputStream对象
oi.close();
}
}
4.21序列化版本号
当java程序中类实现了Serializable
接口,编译器会自动给该类添加一个“序列化版本号”。序列化版本号:serialVersionUID
。在java中分别class首先是通过类名区分,然后是通过序列化版本号区分。
4.22 transient关键字(序列化)
在Java中,transient
关键字用于标记一个字段不应该作为对象的持久状态的一部分进行序列化。当一个类实现Serializable接口时,默认情况下,该类的所有实例字段都会被序列化。然而,有时你可能希望某些字段不被序列化,这时就可以使用transient
关键字。
例如:
public class Person implements Serializable {
private String name;
private int age;
private transient Address address; // 不会被序列化的字段
// 构造方法、getter和setter...
}
在这个例子中,Address
字段不会被序列化。当你试图将这个Person对象序列化时,它的地址信息将不会包含在序列化的数据中。
需要注意的是,transient
关键字只是告诉Java编译器和虚拟机,当程序执行序列化操作时,不要对该变量进行处理,但是它并没有提供具体的替代方案,也没有指定如何处理这些变量。如果你需要对这些变量进行特殊处理,那么你需要自己编写代码来完成。
4.22 打印流PrintStream 和 PrintWriter
PrintStream:
package com.powernode;
import java.io.PrintStream;
/**
* 1. java.io.PrintStream:打印流(专业的负责打印的流,字节形式。)
* 2. PrintStream不需要手动刷新,自动刷新。
*/
public class PrintStreamTest {
public static void main(String[] args) throws Exception {
// 创建一个打印流对象
// 构造方法:PrintStream(OutputStream out)
// 构造方法:PrintStream(String fileName)
PrintStream ps = new PrintStream("log1");
// 没有这样的构造方法。
//PrintStream ps2 = new PrintStream(new FileWriter(""));
//PrintStream ps2 = new PrintStream(new FileOutputStream("log1"));
// 打印流可以打印各种数据类型数据。
// 打印整数100
ps.print(100);
// 打印布尔值false
ps.println(false);
// 打印字符串"abc"
ps.println("abc");
// 打印字符'T'
ps.println('T');
// 打印浮点数3.14
ps.println(3.14);
// 打印字符串"hell world"
ps.println("hell world");
// 打印整数200
ps.println(200);
// 打印字符串
ps.println("\"hello world!\"");
// 定义字符串变量
String name = "张三";
// 定义双精度浮点数变量
double score = 95.5;
// 使用printf方法打印字符串和双精度浮点数
ps.printf("姓名:%s,考试成绩:%.2f", name, score);
// 关闭
ps.close();
}
}
PrintWriter:
package com.powernode;
import java.io.FileWriter;
import java.io.PrintWriter;
/**
* java.io.PrintWriter:专门负责打印的流。(字符形式)
* 需要手动刷新flush。
* PrintWriter比PrintStream多一个构造方法:
* PrintStream构造方法:
* PrintStream(OutputStream)
* PrintWriter构造方法:
* PrintWriter(OutputStream)
* PrintWriter(Writer)
*/
public class PrintWriterTest {
public static void main(String[] args) throws Exception{
// 创建字符打印流
//PrintWriter pw = new PrintWriter(new FileOutputStream("log2"));
// 创建一个PrintWriter对象,用于向文件"log2"中写入数据
PrintWriter pw = new PrintWriter(new FileWriter("log2"), true);
// 打印
pw.println("world hello!!!");
pw.println("zhangsan hello!!!");
// 刷新
//pw.flush();
// 关闭
pw.close();
}
}
4.23 标准输入流
package com.powernode;
import java.io.IOException;
import java.io.InputStream;
public class SysteminTest {
public static void main(String[] args) throws IOException {
// 获取标准输入流
InputStream in = System.in;
// 定义一个变量用于存储读取的字节数
int count ;
// 定义一个字节数组用于存储读取的字节
byte[] bytes = new byte[1024];
// 从标准输入流中读取字节,并存储到字节数组中
count=in.read(bytes);
// 遍历字节数组,输出每个字节
for(int i=0;i<count;i++){
System.out.println(bytes[i]);
}
}
}
结果:
标准输入流改变数据源:
package com.powernode;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* 对于标准输入流来说,也是可以改变数据源的。不让其从控制台读数据。也可以让其从文件中或网络中读取数据。
*/
public class SystemInTest02 {
public static void main(String[] args) throws Exception{
// 修改标准输入流的数据源。
System.setIn(new FileInputStream("log2"));
// 获取标准输入流
InputStream in = System.in;
byte[] bytes = new byte[1024];
int readCount = 0;
while((readCount = in.read(bytes)) != -1){
System.out.print(new String(bytes, 0, readCount));
}
}
}
结果:
使用缓冲流包装标准输入流:
package com.powernode;
import java.io.BufferedInputStream;
import java.io.IOException;
public class SystemInTest03 {
public static void main(String[] args) throws IOException {
// 创建一个BufferedInputStream对象,用于读取标准输入流
BufferedInputStream bs = new BufferedInputStream(System.in);
int count;
// 创建一个byte数组,用于存储读取到的数据
byte[] bytes = new byte[1024];
// 循环读取标准输入流中的数据
while((count=bs.read(bytes))!=-1){
// 将读取到的数据转换为字符串并输出
System.out.println(new String(bytes,0,count));
}
}
}
结果:
4.24 标准输出流
package com.powernode;
import java.io.IOException;
import java.io.OutputStream;
public class SystemoutTest {
// 主方法
public static void main(String[] args) throws IOException {
// 获取System.out的输出流
OutputStream os= System.out;
// 将字符串"hello world"转换为字节数组并写入输出流
os.write("hello world".getBytes());
}
}
5. File类
exist()
: file是否存在,如果存在返回true
,如果不存在返回false
。
createNewFile()
:以新文件形势构建出来
mkdir()
:以目录形式创建
mkdirs()
:创建多级目录
delete()
:删除文件或者目录
getAbsolutepath()
:获取文件绝对路径
getName()
:获取文件名
getParent()
:获取父目录路径
isAbsolute()
:判断该路径是否绝对路径
isFile()
:file是否是文件
isDirectory
:file是否是目录
isHidden()
:判断是否是隐藏文件
lastModified()
:最后修改时间点
long l = file1.lastModified();
Date time = new Date(l);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String str = sdf.format(time);
System.out.println("文件最后修改时间点:" + str);
length()
:文件总字节数
renameTo()
:重命名
listFiles()
:获取所有的子文件,包括子目录。
文件过滤器:listFiles()
File[] files1 = file1.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
/*if (name.endsWith(".mdj")) {
return true;
}
return false;*/
return name.endsWith(".mdj");
}
});
6.Propertise +IO
package com.powernode;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class LoadProperties {
public static void main(String[] args) throws IOException {
// 获取当前线程的类加载器
String path = Thread.currentThread().getContextClassLoader().getResource("jdbc.properties").getPath();
// 创建文件读取器
FileReader fileReader = new FileReader(path);
// 创建Properties对象
Properties properties = new Properties();
// 加载文件中的属性
properties.load(fileReader);
// 输出属性值
System.out.println(properties.getProperty("driver"));
System.out.println(properties.getProperty("password"));
}
}
结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?