IO流
I(Input):输入流指的是将数据以字符或字节形式从外部媒介 比如文件,数据库等读取到内存中
O(Output)输出流指的是将内存中的数据写入外部媒介
IO流概述:流(Stream)源于UNIX中管道(pipe)的概念,在UNIX中,管道是一条不间断的字节流,用来实现程序或进程间的通信,或读写外围设备,外部文件等
字节流概述:字节流是由字节组成的,字节流是最基本的,所有InputStream和OutputStream的子类都是字节流,主要用在处理二进制数据,它是按字节处理的
字符流概述:字符流是由字符组成的,Java里字符由两个字节组成,所有Reader和Writer的子类都是字符流,主要用在处理文本内容或特定字符。
字节流和字符流的区别:
1.读写的时候一个是按字节读写,一个是按字符。
2.需要对内容按行处理,一般会选择字符流。
3.只是读写文件,和文本内容无关的(下载,复制等),一般选择字节流
方法名:
read() 解释:从此输入流中读取下一个数据字节
close() 解释:关闭此输入流并释放与此流关联的所有系统资源
使用FileInputStream将D盘(例:D:/Lenovo/info.txt文件内容输出到控制台上。
读取数据
public class InputStreamDemo {
public static void main(String[] args) {
try {
FileInputStream input=new FileInputStream("/D:/Lenovo/Hello.txt");
try {
int n=input.read();
while(n>-1){
System.out.print((char)n);
n=input.read();
}
input.read();//关闭流
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
FileInputStream input=new FileInputStream("/D:/Lenovo/Hello.txt");
try {
int n=input.read();
while(n>-1){
System.out.print((char)n);
n=input.read();
}
input.read();//关闭流
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
写入数据
public class OutputStreamDemo {
public static void main(String[] args) {
try {
String hello="Hello China";
FileOutputStream out=new FileOutputStream("D:/Lenovo/Z.txt");
out.write(hello.getBytes());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
String hello="Hello China";
FileOutputStream out=new FileOutputStream("D:/Lenovo/Z.txt");
out.write(hello.getBytes());
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
替换数据:
public class Test {
public static void main(String[] args) {
try {
FileInputStream input=new FileInputStream("/D:/Lenovo/Hello.txt");
FileOutputStream output=new FileOutputStream("D:/Lenovo/Z.txt");
int n=input.read();
while(n>-1){
output.write(n);
n=input.read();
}
output.close();
input.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
FileInputStream input=new FileInputStream("/D:/Lenovo/Hello.txt");
FileOutputStream output=new FileOutputStream("D:/Lenovo/Z.txt");
int n=input.read();
while(n>-1){
output.write(n);
n=input.read();
}
output.close();
input.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}