IO流文件操作(java)

FileInputStream
该流用于从文件读取数据,它的对象可以用关键字 new 来创建。

有多种构造方法可用来创建对象。

File f = new File(“new.txt”);
FileInputStream fa = new FileInputStream(f);

或者

FileInputStream fa = FileInputStream(“new.txt”);

创建了InputStream对象,就可以使用下面的方法来读取流或者进行其他的流操作。

1 public void close() throws IOException{}
关闭此文件输入流并释放与此流有关的所有系统资源。抛出IOException异常。
2 protected void finalize()throws IOException {}
这个方法清除与该文件的连接。确保在不再引用文件输入流时调用其 close 方法。抛出IOException异常。
3 public int read(int r)throws IOException{}
这个方法从 InputStream 对象读取指定字节的数据。返回为整数值。返回下一字节数据,如果已经到结尾则返回-1。
4 public int read(byte[] r) throws IOException{}
这个方法从输入流读取r.length长度的字节。返回读取的字节数。如果是文件结尾则返回-1。
5 public int available() throws IOException{}
返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取的字节数。返回一个整数值。

import java.io.*;

//专用于文件信息输出(in)
public class FileInputStream使用 {
	public static void main(String[] args) throws IOException {
		//创建文件对象
		File f = new File("Myname.txt");
		//创建输入流
		FileInputStream fa = new FileInputStream(f);
		//它使用指定的 charset 读取字节并将其解码为字符
		InputStreamReader reader = new InputStreamReader(fa,"UTF-8");
		
		//定义字符串变量
		StringBuffer buf = new StringBuffer();
		//依次将读取到的信息转为字符加入字符串
		while(reader.ready()) {
			buf.append((char)reader.read());
		}
		System.out.println(buf.toString());
		
		fa.close();
		reader.close();
	}
}

FileOutputStream
该类用来创建一个文件并向文件中写数据。

如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件。

有两个构造方法可以用来创建 FileOutputStream 对象。

使用字符串类型的文件名来创建一个输出流对象:

File f = new File(“new.txt”);
FileOutputStream fa = new FileOutputStream(f);

或者

FileOutputStream fa = FileOutputStream(“new.txt”);

创建OutputStream 对象完成后,就可以使用下面的方法来写入流或者进行其他的流操作。

1 public void close() throws IOException{}
关闭此文件输入流并释放与此流有关的所有系统资源。抛出IOException异常。
2 protected void finalize()throws IOException {}
这个方法清除与该文件的连接。确保在不再引用文件输入流时调用其 close 方法。抛出IOException异常。
3 public void write(int w)throws IOException{}
这个方法把指定的字节写到输出流中。
4 public void write(byte[] w)
把指定数组中w.length长度的字节写到OutputStream中。

import java.io.*;

//专用于文件信息输入(out)
public class FileOutputStream使用 {
	public static void main(String[] args) throws IOException {
			File myFile = new File("Myname.txt");
			//建立文件对象
			FileOutputStream fout = new FileOutputStream(myFile);
			//建立输出流用于写文件(若没有此文件会在指定位置自动生成)
			OutputStreamWriter write = new OutputStreamWriter(fout,"UTF-8");
			//创建使用给定字符集编码器的 OutputStreamWriter。 
			
			write.append("scs ");
			write.append("dsv ");
			write.append("brer");
			//将信息写入文件
			
			write.close();
			fout.close();
			//关闭文件
			//结束输出流使用
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值