IO字节流
一、字节输出流OutputStream
java.io.OutputStream //抽象类:表示输出字节流的所有类的超类。定义了一些子类共性的成员方法
public void close();
public void flush();
public void write();
public void write();
public void write()
1.字节输出流写入数据到文件
java.io.FileOutputStream extends OutputStream //文件字节输出流,把内存中的数据写入到硬盘文件中
1.1构造方法
FileOutputStream(String name)
//创建一个向具有指定名称的文件中写入数据的输出文件流
FileOutputStream(File file)
//创建一个向指定 File 对象表示的文件中写入数据的文件输出流。
作用:
-
创建一个FileOutputStream 对象
-
会根据构造方法中传递的文件/文件路径,创建一个空的文件
-
会把FileOutputStream对象指向已经创建好的文件。
1.2写入数据的原理
java程序 JVM OS OS调用写数据的方法 写入数据
2.字节输出流的使用步骤
-
创建一个FileOutputStream对象,构造方法传入数据的目的地。
-
调用FileOutputStream对象中的方法write,把数据写入到文件
-
释放资源(流使用会占用一定内存)
public class FileOutputStreamDemo {
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("a.txt");
fos.write(97);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}//-->a
注意:
文本编辑器会把字节变为字符,0-127 ASCII 码表 中文查GBK
3.字节输出流写多个字节
FileOutputStream fos = new FileOutputStream("a.txt");;
byte[] bytes= {82,28,27,24,87};
fos.write(bytes);
byte[] bytes2= "你好".getBytes();
fos.write(bytes2);
public void write(byte[] b,
int off,
int len)
throws IOException将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此文件输出流。
4.追加写和换行写
FileOutputStream**(String name, boolean append)
创建一个向具有指定 name
的文件中写入数据的输出文件流。
FileOutputStream**(File file, boolean append)
创建一个向指定 File
对象表示的文件中写入数据的文件输出流。
写换行:
- windows: \r\n
- linux: /n
- mac: /r
二、字节输入流InputStream
public abstract class InputStream extends Objectimplements Closeable
此抽象类是表示字节输入流的所有类的超类。
1.FileInputStream
public class **FileInputStream **extends InputStream
- FileInputStream从文件系统中的某个文件中获得输入字节。哪些文件可用取决于主机环境
FileInputStream
用于读取诸如图像数据之类的原始字节流。要读取字符流,请考虑使用 FileReader
1.构造方法
FileInputStream(String name)
通过打开一个到实际文件的连接来创建一个 FileInputStream
,该文件通过文件系统中的路径名 name
指定
FileInputStream**(File file)
通过打开一个到实际文件的连接来创建一个 FileInputStream
,该文件通过文件系统中的 File
对象 file
指定。
二、读取字节数据
java程序 JVM OS OS调用读数据的方法 读取数据
1.使用步骤
创建FileInputStream对象,构造方法中绑定要读取的数据源。
使用方法read读取数据
释放资源。
2.实例
public class FileInputStreamDemo {
public static void main(String[] args) {
try {
FileInputStream fis=new FileInputStream("E:\\learning\\20190222javaee 博学谷\\test\\a.txt");
int len=0;
while ((len=fis.read())!=-1){
System.out.println((char)len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.读取一个字节的原理
4.字节流一次读取第一个字节
int read(byte[] b) //从输入流中读取一定数量的字节,并将其存在缓冲区数组b 中。
返回值:代表每次读取的有效字节数
byte[] b:存放每次读取的字节内容
public class FileInputStreamByte {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("E:\\learning\\20190222javaee 博学谷\\test\\a.txt");
byte[] bt = new byte[2];
int len=fis.read(bt);
System.out.println(len);
while ((len=fis.read(bt))!=-1){
System.out.println(Arrays.toString(bt));
//new String(bt,0,len);
}
fis.close();
}
}