文件与流

1、流的分类

1)输入流和输出流:数据“流入”程序的成为“输入”。

2)字节流和字符流:指存取数据的最小单位

3)节点流(Node Stream)和处理流(Processing Stream):节点流直接连接到数据源,处理流是对一个已存在的流的连接和封装,通过所封装的流的功能调用实现增强的数据读写功能,它并不直接连到数据源.

2、流的基类

1)字节流基类:InputStream和OutputStream

2)字符流基类:Reader和Writer

 

 

 *****输入流

public class FileInputStreamTest {

public static void main(String[] args) throws IOException {

//创建字节输入流
FileInputStream fis = new FileInputStream("FileInputStreamTest.java");
byte[] bbuf = new byte[1024];
//用于保存实际读取的字节数
int hasRead = 0;
while ((hasRead = fis.read(bbuf)) > 0) {
System.out.print(new String(bbuf, 0, hasRead));
}
fis.close();
}
}

*****输出流

public class FileOutputStreamTest {

public static void main(String[] args) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
//创建字节输入流
fis = new FileInputStream("FileOutputStreamTest.java");
//创建字节输入流
fos = new FileOutputStream("newFile.txt");
byte[] bbuf = new byte[32];
int hasRead = 0;
//循环从输入流中取出数据
while ((hasRead = fis.read(bbuf)) > 0) {
//每读取一次,即写入文件输出流,读了多少,就写多少。
fos.write(bbuf, 0, hasRead);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
//使用finally块来关闭文件输入流
if (fis != null) {
fis.close();
}
//使用finally块来关闭文件输出流
if (fos != null) {
fos.close();
}
}
}
}

posted @ 2020-11-11 21:14  往心。  阅读(84)  评论(0编辑  收藏  举报