JAVA的FileOutput/InputStream使用实例

在JAVA中,要读写文件,要使用Stream这个东西。

Stream简单来说,可以看做在程序和文件之间打开了一个管道,然后把数据通过这个管道输送到文件或程序中去。

FileOutput/InputStream,只支持以字节流的形式输入输出。

下面是一个向文件输入数据和从文件读取数据并打印的屏幕上的实例:

File file = new File("test.txt");

//实例化输出流
FileOutputStream op = new FileOutputStream(file);

//只支持以字节流的形式输入
//既是write只能将byte数组的内容写到文件中
op.write("www.sina.com.cn".getBytes()); //把字符串转化为字节数组并写入到流中

op.close();

//关闭输出流

//实例化输入流
FileInputStream in = new FileInputStream(file);

byte[] buf = new byte[1024];

//将文件内容读入到byte数组中,返回读到的数据的长度。
int len = in.read(buf);

//以byte数组来构建一个字符串,偏移量为0,长度为len
String result = new String(buf,0,len-1);
//可以看看len-1的效果,最后少了一位

System.out.println(result);

原文地址:https://www.cnblogs.com/wzben/p/5024874.html