Java 读写文件
输入流和输出流的类层次图
FileInputStream
该流用于从文件读取数据。
我们可以使用 new 关键字来创建一个 FileInputStream 对象。
FileInputStream 提供了许多构造方法:
-
可以使用字符串类型的文件名来创建一个输入流对象来读取文件。
InputStream f = new FileInputStream(“C:/java/hello”);
-
可以使用一个文件对象来创建一个输入流对象来读取文件,
不过我们首先得使用 File() 方法来创建一个文件对象。File f = new File(“C:/java/hello”);
InputStream out = new FileInputStream(f);
当我们有了 FileInputStream 对象后,就可以调用下面的方法来读取流或者进行其他的流操作
方法及描述:
-
关闭此文件输入流并释放与此流有关的所有系统资源,抛出IOException异常。
public void close() throws IOException{}
-
这个方法清除与该文件的连接,确保在不再引用文件输入流时调用其 close 方法。抛出 IOException 异常。
protected void finalize()throws IOException {}
-
这个方法从 InputStream 对象读取指定字节的数据,返回为整数值,返回下一字节数据,如果已经到结尾则返回 -1。
public int read(int r)throws IOException{}
-
这个方法从输入流读取r.length长度的字节,返回读取的字节数,如果是文件结尾则返回 -1。
public int read(byte[] r) throws IOException{}
-
返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取的字节数,返回一个整数值。
public int available() throws IOException{}
FileOutputStream
FileOutputStream 类用来创建一个文件并向文件中写数据。
如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件。
有两个构造方法可以用来创建 FileOutputStream 对象:
-
使用字符串类型的文件名来创建一个输出流对象。
OutputStream f = new FileOutputStream("/tmp/hello.txt")
-
可以使用一个文件对象来创建一个输出流来写文件,
首先得使用 File() 方法来创建一个文件对象。
File f = new File(“C:/java/hello”);
OutputStream f = new FileOutputStream(f);创建 OutputStream 对象完成后,就可以使用下面的方法来写入流或者进行其它 的流操作。
方法及描述:
-
关闭此文件输入流并释放与此流有关的所有系统资源,抛出IOException异常。
public void close() throws IOException{}
-
清除与该文件的连接,确保在不再引用文件输入流时调用其 close 方法,抛出IOException异常。
protected void finalize() throws IOException {}
-
把指定的字节写到输出流中。
public void write(int w) throws IOException{}
-
把指定数组中 w.length 长度的字节写到 OutputStream 中。
public void write(byte[] w)
InputStream 和 OutputStream 的用法演示:
代码如下:
import java.io.*;
public class FileStreanTest {
public static void main(String[] args) throws IOException {
File f = new File("test.txt");
// 构建FileOutputStream对象,文件不存在会自动新建
FileOutputStream fileOutputStream = new FileOutputStream(f);
// 构建OutputStreamWriter对象,参数可以指定编码,默认为操作系统默认编码,windows上是gbk
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"UTF-8");
// 写入到缓冲区
outputStreamWriter.append("中文输入");
//换行
outputStreamWriter.append("\r\n");
outputStreamWriter.append("EnglishOutput");
//关闭写入流,同时会把缓冲区内容写入文件,所以上面的注释掉
outputStreamWriter.close();
// 关闭输出流,释放系统资源
fileOutputStream.close();
// 构建FileInputStream对象
FileInputStream fileInputStream = new FileInputStream(f);
// 构建InputStreamReader对象,编码与写入相同
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
StringBuffer stringBuffer = new StringBuffer();
// 转成char加到StringBuffer对象中
while(inputStreamReader.ready()){
stringBuffer.append((char) inputStreamReader.read());
}
System.out.println(stringBuffer.toString());
// 关闭读取流
inputStreamReader.close();
// 关闭输入流,释放系统资源
fileInputStream.close();
}
}