1.输入输出概念
1.I(input)O(output):
把电脑硬盘上的数据读到程序中,称为输入(input),进行文件的read操作;从程序往外部设备写数据,称为输出(output),进行数据的write操作。
2.输入流(Input Stream):
程序从输入流读取数据源,数据源包括外界(键盘、文件、网络……),即是将数据源读到程序的通信通道。
所有输入流都是InputStream类或者Reader类的子类。
类名以InputStream结尾的类都是InputStream的子类。
类名以Reader结尾的都是Reader类的子类。
3.输出流(Output Stream):
程序向输出流写入数据,将程序中的数据出输出到外界的通信通道。
所有输出流都是OutputStream类或者Writer类的子类。
类名以OutputStream结尾的类都是OutputStream类的子类。
类名以Writer结尾的类都是Writer类的子类。
4.InputStream和OutputStream的子类都是字节流:可以读写二进制文件,主要处理音频、图片、歌曲、字节流处理单元为一个字节。字节流将读取到的字节数据,去指定的编码表中获取对应文字。
5.Reader和Writer的子类都是字符流:主要处理字符或字符串,字符流处理单元为2个字节。
2.字节输入/输出流
1.字节流中的常用类:
输入流:FileInputStream
输出流:FileOutputStream
2.InputStream的基本方法:
(1)int read() throws IOException 读取一个字节并以整型的形式返回(0~255),如果返回-1已到输入流的结尾。
(2)int read(byte[] buffer) throws IOException 读取一系列字节并存储到一个byte数组buffer,返回实际读取的字节数,如果读取前已到输入流的末尾返回-1。
(3)void close() throws IOException 关闭流释放内存资源。
3.OutputStream的基本方法:
(1)void write(int b) throws IOException 向输出流中写入一个字节数据,该字节数据为参数b的低8位。
(2)void write(byte[] b,int off,int len) throws IOException 将一个字节类型的byte数组中的从指定位置(off)开始到len个字节写入到输出流。
(3)void close() throws IOException 关闭流释放内存资源。
public class IOStreamDemo {
//文件字节输入定义缓冲区时用小写byte
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
//文件输入流
try {
in = new FileInputStream("H:\\java测试\\1.txt");
int i = 0;
while ((i = in.read())!=-1){
System.out.println(i);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(in != null){
in.close();
}
}
//文件输出流
try {
out = new FileOutputStream("H:\\java测试\\2.txt");
for(int i=97;i<115;i++){
out.write(i);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if(out != null){
out.close();
}
}
}
}
向文件输出时,如果文件中以前有内容,则新输出的内容会覆盖以前的内容。