IO
File类:java中用来对文件或目录进行抽象的类(常见方法详见jdk)
IO流:java内部提供的,用来从数据源进行数据传输操作的类。
流:是个抽象的概念,是一连串动态的数据的集合
数据源:数据的来源
目的地:数据最终要输出的地方
分类:
1.以流向分(通常是以程序为中心)
输入流
输出流
2.按操作单元分:
字节流(万能的流,可以用字节的形式传输一切数据)
字符流(以字符为单位)
3.按功能分
节点流:负责数据的输入输出
处理流:负责对流进行处理(增强等)
InputStream:字节输入流,是一个抽象类,下有很多子类。一般使用多态调用子类方法。
例子:
File file=new File("D://homework//笔记//方法.txt");
InputStream in=new FileInputStream(file);//从该处向程序写入数据
byte []car=new byte[1024];//以二进制存入byte数组中
int len=-1;//每次读取的个数
while((len=in.read(car))!=-1){ //read()方法会返回每次读到的数据的个数,读完之后则会返回-1
System.out.println(new String(car,0,len, StandardCharsets.UTF_8));
}
in.close();
OutputStream:字节输出流,是一个抽象类,下有很多子类。一般使用多态调用子类方法,向外输出
例子:
import java.io.*;
public class TestOutput {
public static void main(String[] args) {
OutputStream os=null;
InputStream in=null;
{
try {
in=new FileInputStream("D://test.jpg");
os = new FileOutputStream("D://testcopy.jpg");
byte [] data=new byte[1024*2];
int len=-1;
while ((len=in.read(data))!=-1){
os.write(data,0,len);
}
os.flush();//注意:每次输出完毕,必须强制刷出剩余内容
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(in!=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();//注意:必须是先开的后关!!
}
}
}
}
}
}
注意:
写出内容默认覆盖源文件内容(FileOutputStream (File file, boolean append) 参数append是否追加数据,默认不追加覆盖,true->追加)
目标文件不存在系统会默认构建
目标文件所在的路径不存在,系统不会构建
字符流:该读入输出的方式都是以每个字符为单位,使用方法和字节流大同小异。
Reader字符输入流:是一个抽象类,下有很多子类。一般使用多态调用子类方法。
Writer字符输出流:是一个抽象类,下有很多子类。一般使用多态调用子类方法。
例子:
import java.io.*;
public class TestReader {
public static void main(String[] args) {
Reader re=null;
Writer wr=null;
try {
re=new FileReader("D://homework//笔记//方法.txt");
wr=new FileWriter("D://ddd.txt");
char [] data=new char[1024];//因为是字符流,按照字符读入写出,和字节流不同之处
int len=-1;
while ((len= re.read(data))!=-1){
wr.write(data,0,len);
}
wr.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(wr!=null){
try {
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(re!=null){
try {
re.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

浙公网安备 33010602011771号