输入输出:
字节输入输出流:每次只操作一个字节(读取或写入),字节操作流,默认每次执行写入操作会直接把数据写入文件.
io流:
输入流:Input;
输出流:Output
字节输出流:
OutputStream:此为抽象类,所有输出字节流的超类,向文件中输出使用FileOutputStream类;
字节输入流:
InputStream:所有字节输入流的超类,向程序输入使用FileInputStream;
输出:
//输出流
public class OutputStream1 {
public static void main(String[] args) throws IOException {
File f1=new File("d:/aa");
File f2=new File("a.txt");
f1.mkdirs();
f2.createNewFile();
//使用OutPutStream输出流完成对文件的的写入操作 内存输出到文件
OutputStream out=new FileOutputStream(f2);
out.write(97);
byte[] bytes={97,98,99,100};
out.write(bytes);//按照ASCII码表解析数组写入文件写入ABCD
out.write(bytes,1,2);
}
}
//FileWrite
String msg="世界灿烂盛大";
byte[] bytes=msg.getBytes();//获取字符串对应解析后的byte数组
out.write(bytes);
输入:
//输入流
public class InputTest1 {
public static void main(String[] args) throws IOException {
//输出流:内存的内容输出到文件(写操作)输入流:文件内容输入到内存中(读操作)
File f1=new File("d:/a.txt");
//创建一个输入流,读取f1这个文件
InputStream input=new FileInputStream(f1);
//读取文件的一个字符,然后把字符转换为对应的数字返回,如果读取到文件的末尾,返回的是-1
int n;
while((n= input.read())!=-1){
System.out.print((char) n);
//缓冲区
byte[] b=new byte[10];
int n1=input.read(b);
String s=new String(b,0,n1);
System.out.println(s);
}
}
}
// FileRead
byte[] b=new byte[10];
int n1=input.read(b);
String s=new String(b,0,n1);
System.out.println(s);
综合案例:文件的复制
public static void main(String[] args) throws IOException {
//1.定义源文件和目的文件的文件对象
File f1=new File("D:/a.txt");
File newFile=new File("D:/aa/copy.txt");
//2.创建目的文件
newFile.createNewFile();
//3.定义输入输出流:使用输入流读取内容使用输出流写入内容
InputStream in=new FileInputStream(f1);
OutputStream out=new FileOutputStream(newFile);
//4.循环读取文件内容,同时写入指定的文件
/*
int n;
while((n=in.read())!=-1){
out.write(n);
}
*/
//实际工作中推荐的写法
/*
*byte[] buffer=new byte[10];
* int n=0;
* while((n=in.read(buffer))!=-1){
* out.write(buffer,0,n);//把buffer数组从0开始,截取读取到有效数字节数n,写入到目的文件中
* }
*
*/
//练习是最容易理解的方式
byte[] buffer=new byte[10];
int n1=0;
while(true){
n1=in.read(buffer);//读取文件,内容放入buffer数组中,返回的实际读取的字节数
if(n1!=1){
out.write(buffer,0,n1);//把buffer数组从0开始,截取读取到有效字节数n 写入到目的文件中
}else{
break;
}
}
}