梦入琼楼寒有月,行过石树冻无烟

JAVA IO

I/O即input/output 输入/输出,通常指数据在内部存储器和外部存储器或其他周边设备内进行输出.

字节流

​ 程序使用字节流执行8位的输入(input)和输出(output).而所有字节流最小的单元为字节

1
2
java.io.FileInputStream
java.io.FileOutpuStream

将1.txt文件内容写入\覆盖到2.txt之中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Demo {
public static void main (String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("/home/sunli/1.txt");
out = new FileOutputStream("/home/sunli/2.txt");
int i;
// in.read从此输入流中读取一个字节数据据
while((i = in.read()) !=-1) {
// 将指定的字节写入此文件输出流。
out.write(i);
}
} finally {
// finally 将处理收尾工作
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}

字符流

字符流是以16位作为数据单元数据流中的最小数据单元就是单元字符,也就是Unicode每位即占2位字符

Writer

​ writer是所有输出字符流的父类.是一个抽象的类;

​ CharArrayWriter\StringWriter是两种基本介质流,分别想char\String中写入数据.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 写单个字符
public void write(int c) throws IOException;

// 将字符数组cbuf[] 写到输出流
public void write(char cbuf[]) throws IOException

// 将字符数组cbuf[]中的从索引为off的位置处开始的len字符写入输出流
public abstract void write(char cbuf[],int off,int len) throws IOException

// 将字符串str中的字符写入输出流
public void write(String str) throws IOException;

// 将字符串str中从索引off处的len字符写入输出流中
public void write(String str,int off,int len) throws IOException

读取文件内信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Demo {
public static void main (String args[]) throws IOException {
FileReader reader = null;
try {
File readFile = new File("/home/sunli/1.txt");
reader = new FileReader(readFile);

// length 返回由该抽象路径名表示的文件长度。如果该路径名表示目录,则 返回值未指定。
char [] byteArray = new char[(int) readFile.length()];
int size = reader.read(byteArray);
System.out.println(new String(byteArray));
} catch (Exception e) {
e.printStackTrace();
} finally {
reader.close();
}
}
}

非流式部分

​ 非流式部分主要包含一些辅助流式部分的类,如:SerializablePermission\File\RandomAccessFile\FileDescriptor

读取目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.io.*;

public class Demo {
public static void main (String args[]) {
String dir = "/home/";
File f = new File(dir);
if(f.isDirectory()) {
String s[] = f.list();
for (int i = 0; i <s.length;i++) {
if(f.isDirectory()) {
System.out.println("/" + s[i]);
}
}
}
}
}
⬅️ Go back