在 Java 语言 中,所有的数据都是以流的方式进行传输或者保存的,程序需要数据的时候要使用输入流读取数据,而当程序需要将一些数据保存起来的时候就需要使用输出流。
Java 语言对文件进行操作的时候是以流的方式进行操作的,主要有如下步骤:
和字节不同点在于,字符是 char 格式,一个字符等于两个字节。Java 语言中主要提供流 Reader 和 Writer 两个类专门操作字符流。
Writer 是一个抽象类,它是一个字符输出类。Writer 类常用方法:
方法 | 名称 |
---|---|
abstract public void close() throws IOException; | 关闭输出流 |
public void write(String str) throws IOException | 将字符串输出 |
public void write(char cbuf[]) throws IOException | 将字符串数组输出 |
abstract public void flush() throws IOException; | 强制性清空缓存 |
package com.haicoder.net.stream;
import java.io.*;
public class WriterTest {
public static void main(String[] args) throws Exception {
System.out.println("嗨客网(www.haicoder.net)");
File file = new File("/Users/haicoder/Documents/code/hai/filetest.txt"); //如果文件不存在,会自动创建
Writer writer = new FileWriter(file);
String appendInfo = "嗨客网,你好啊!\r\n"; //\r\n 在追加文件的时候,表示换行
writer.write(appendInfo); //文件没有,创建并写入
writer.write(appendInfo); //追加文件内容
writer.close();
System.out.println("===结束==");
}
}
运行结果如下
创建文件效果如下
在对文件操作的时候,我们需要捕获异常,为了方便,我们在方法体外面 throws Exception。我们使用了Writer 类的子类 FileWriter 来创建对象。 Writer 可以将字符串直接写入到文件中,也可以将信息追加到文件里面。
Reader 类也是一个抽象类,它与 Writer 相反,是一个字符输入类,Reader 类常用方法:
方法 | 描述 |
---|---|
abstract public void close() throws IOException; | 关闭输出流 |
public int read() throws IOException | 读取单个字符 |
public int read(char cbuf[]) throws IOException | 将内容读取到字符数组中,返回读入的长度 |
package com.haicoder.net.stream;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
public class ReaderTest {
public static void main(String[] args) throws Exception {
System.out.println("嗨客网(www.haicoder.net)");
File file = new File("/Users/haicoder/Documents/code/hai/filetest.txt"); //如果文件不存在,会自动创建
System.out.println("====第一种读取方式========");
Reader reader = new FileReader(file);
char c[] = new char[1024];
int len = reader.read(c);
reader.close();
System.out.println("内容为:\n" + new String(c, 0, len));
System.out.println("=========第二种读取方式========");
Reader reader1 = new FileReader(file);
int contentLen = 0;
char contentChar[] = new char[1024];
int tmp = 0;
while ((tmp = reader1.read()) != -1) { //如果为 -1 表示读取到文件内容末尾
contentChar[contentLen] = (char) tmp;
contentLen++;
}
reader1.close();
System.out.println("第二种读取内容为:\n" + new String(contentChar, 0, contentLen));
}
}
运行结果如下:
在对文件操作的时候,我们需要捕获异常,为了方便,我们在方法体外面 throws Exception。我们使用了Reader 类的子类 FileReader 来创建对象。
可以通过一次性读取文件的格式,将所有的内容填写到字节数组中,也可以 read() 方法,一个一个字节读取,如果读取到的数据为 -1 表示已经读取到文件末尾。
字符流里面,输出流是 Writer ,它可以将字节信息填写到文件里面,Reader 是输入流,它可以将文件中的内容读取。Writer 和 Reader 是抽象类,如果要使用它们的方法或者定义它们的对象,需要使用它们的子类。