1、IO概述
字节输入输出流:每次只操作一个字节 (读取或写入),字节操作流,默认每次执行写入操作会直接把数据写入文件.
IO的分类
IO流:
输入流:Input:只能从中读取数据,而不能向其写入数据。一般用于将数据从网络、硬盘读取到内存中。
输出流:Output:只能向其写入数据,而不能从中读取数据。一般用于将数据从内存中写入到网络、硬盘。
格局数据的类型分为:字节流和字符流。
- 字节流 : 以字节为单位,读写数据的流。
- 字符流 : 以字符为单位,读写数据的流。
常用代码:
public void close();//关闭此输入流并释放与此流相关的任何系统资源。
public abstract int read();//从输入流读取数据的下一个字节
public int read(byte[]b);//从输入流中读取一些字节数,并将他们存储到字节数组b中
FileInputStream类
public static void main(String[] args) throws IOException {
//输入流:内存的内容输出到文件(写操作) 输出流:文件内容输入到内存中(读操作)
File f1=new File("C:/aa");
f1.mkdirs();
File f2=new File(f1,"a.txt");
f2.createNewFile();
InputStream input= new FileInputStream(f2);
//读取文件的一个字符,然后把字符转换为对于的数字返回,如果读取到文件尾部,返回-1
int n;
while((n=input.read())!=-1){
System.out.println((char)n);
}
}
缓冲区循环读取内容
public static void main(String[] args) throws IOException {
//输入流:内存的内容输出到文件(写操作) 输出流:文件内容输入到内存中(读操作)
File f1=new File("C:/aa");
f1.mkdirs();
File f2=new File(f1,"a.txt");
f2.createNewFile();
InputStream input= new FileInputStream(f2);
//读取文件的一个字符,然后把字符转换为对于的数字返回,如果读取到文件尾部,返回-1
int n;
byte[] b=new byte[10];
//使用read(byte [] b) 缓冲区循环读取内容
while((n=input.read(b))!=-1){
String s=new String(b,0,n);//从0开始,截取有效的字节n
System.out.println(s);
}
}
FileOutputStream类
控制台录入
public static void main(String[] args) throws IOException {
//输入流:内存的内容输出到文件(写操作) 输出流:文件内容输入到内存中(读操作)
File f1=new File("C:/aa");
f1.mkdirs();
File f2=new File(f1,"w.txt");
f2.createNewFile();
OutputStream out=new FileOutputStream(f2,true);
Scanner sc=new Scanner(System.in);
System.out.println("请输入:");
String msg=sc.next();
byte[]bytes =msg.getBytes();//获取字符串,解析成btye数组
System.out.println(Arrays.toString(bytes));
out.write(bytes);
}
输出指定内容
public static void main(String[] args) throws IOException {
//输入流:内存的内容输出到文件(写操作) 输出流:文件内容输入到内存中(读操作)
File f1=new File("C:/aa");
f1.mkdirs();
File f2=new File(f1,"w.txt");
f2.createNewFile();
OutputStream out=new FileOutputStream(f2,true);
String msg="千年的呼唤";
byte[]bytes =msg.getBytes();//获取字符串,解析成btye数组
System.out.println(Arrays.toString(bytes));
out.write(bytes);
}
例题:
public class myfunction {
public static void main(String[] args) {
try {
//创建文件对象
File file = new File("D:\\test.txt");
//创建文件输入流
FileInputStream fis = new FileInputStream(file);
//创建文件输出流
FileOutputStream fos = new FileOutputStream("D:\\test1.txt");
//创建字节数组
byte[] b = new byte[1024];
//读取文件
int len = fis.read(b);
//写入文件
fos.write(b, 0, len);
//关闭流
fis.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}