java中常用的io流有16种:
FileInputStream
FileOutputStream
FileReader
FileWriter
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
DataInputStream
DataOutputStream
ObjectInputStream
ObjectOutputStream
PrintWriter
PrintStream
用UML简单分析一下他们之间的继承关系:
●FileInputStream与FileOutputStream用法:
package io;
import java.io.File;
import java.io.FileInputStream;
public class FileInputStream01 {
/**
* 输入流FileInputStream
* 将D盘test01.txt,读到内存
*/
public static void main(String[] args) throws Exception{
File file = new File("D:\\test01.txt");
FileInputStream fis = new FileInputStream(file);
int temp = 0; //读取的字节数
byte[] bytes = new byte[1024]; //将1024个字节的数据读入一个 byte 数组中
while((temp=fis.read(bytes))!=-1){
System.out.println(temp);
//将byte数组转换为字符串输出
System.out.print(new String(bytes,0,temp));
}
fis.close();
}
}
package io;
import java.io.FileOutputStream;
public class FileOutputStream01 {
/**
* 输出流 FileOutputStream
* 将内存中str字符串写入D盘test02.txt中
*/
public static void main(String[] args) throws Exception{
//设置为true,不会将原文件内容覆盖
FileOutputStream fos = new FileOutputStream("D:\\test02.txt",true);
String str = "helloword";
//将String转换为byte数组
byte[] bytes = str.getBytes();
fos.write(bytes);
//强制写入,为了保证数据的完整性
fos.flush();
fos.close();
}
}
package io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileCopy {
/**
* 关于文件的复制粘贴
* 将D盘test02.txt,复制粘贴到C盘
*/
public static void main(String[] args) throws Exception{
//创建输入流
FileInputStream fis = new FileInputStream("D:\\test02.txt");
//创建输出流
FileOutputStream fos = new FileOutputStream("C:\\test02.txt");
int temp = 0;
byte[] bytes = new byte[1024];
while((temp=fis.read(bytes))!=-1){
fos.write(bytes,0,temp);
}
fos.flush();
fis.close();
fos.close();
}
}