InputStream:所有字节输入所有类的超类
OuputStream:所有字节输出类的超类
字节流写数据
FileOutputStream fos = new FileOutputStream("D\\JavaTest\\2.txt");
//1)调用系统创建了文件 2)创建了字节流输出对象 3)将字节流对象指向创建好的文件
//在文件中输入指定的字符
fos.write(97);
//释放资源
fos.close();
三种写数据方式
void write(int b)
void write(byte[] b)
void write(byte[],int off,int len)
FileOutputStream fos = new FileOutputStream("D:\\FileTest\\2.txt");
fos.write(97);
byte[] b = new byte[]{97,98,99,100,111,56,88};
fos.write(b);
String str = "zhangsan1lisi1";
byte[] b2 = str.getBytes();
fos.write(b2,1,10);
//释放资源
fos.close();
以追加的方式进行写文件
public FileOutputStream(String name,boolean append)//append为true为追加
FileOutputStream fos = new FileOutputStream(“D:\FileTest\2.txt”,true);
字节流读数据
FileInputStream:从文件中读取数据
FileInputStream fis = null;
try {
fis = new FileInputStream("D:\\FileTest\\2.txt");
//第一次读取数据
int by ;
while((by = fis.read()) != -1) {
System.out.print((char)by);
}
fis.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}finally {
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
用字节将一个文件内容复制到另外一个文件的实例
FileInputStream fis = new FileInputStream("D:\\FileTest\\2.txt");
FileOutputStream fos = new FileOutputStream("D:\\FileTest\\3.txt",true);
int by;
while((by = fis.read())!= -1){
fos.write((byte)by);
}
fis.close();
fos.close();
一次性读取一个数组
/**
* 一次读取一个字符数组
*/
public class IODemo2 {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("D:\\FileTest\\2.txt");
byte[] bys = new byte[1024];
int num;
while((num = fis.read(bys)) != -1) {
System.out.println(new String(bys,0,num));
}
fis.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
将图片复制到另外一个位置
public static void main(String[] args) throws IOException{
FileInputStream fis = new FileInputStream("D:\\FileTest\\1.jpg");
FileOutputStream fos = new FileOutputStream("D:\\FileTest\\2.jpg");
byte[] bys = new byte[1024];
int num;
while ((num = fis.read(bys)) != -1){
fos.write(bys,0,num);
}
fis.close();
fos.close();
}
字节缓存流的使用
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D:\\FileTest\\bos.txt"));
bos.write("abcd\r\n".getBytes());
bos.write("efgh".getBytes());
bos.close();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\FileTest\\bos.txt"));
int by;
while ((by = bis.read())!=-1){
System.out.print((char) by);
}
bis.close();