IO:
根据数据的流向分为:输入流和输出流。
- 输入流 :把数据从
其他设备
上读取到内存
中的流。 - 输出流 :把数据从
内存
中写出到其他设备
上的流。
根据数据的类型分为:字节流和字符流。
- 字节流 :以字节为单位,读写数据的流。
- 字符流 :以字符为单位,读写数据的流。
创建文本输入流:
构造方法:OutputStrean out new FileOutStream("D:\\test\\创建文件的名字");
方法:
out.write(100) 输入的是byte型会自动按照ascll转为char型也就是b
out.write('1')输入的是char型不会转了
byte[] byte1={48,49,50}
out.write(bytes):将数组传入
out.write(bytes,1,2):将数组的缩影1到2传入
out.close():关闭输入流,为什么呢因为底层是navite会一直占用这个文件要用close关闭
OutputStrean out =new FileOutputStrean("文件目录",true):true的意思是创建文件时如果有重复的则会在原本上续写而不是覆盖
使用try抛出:为什么要用这个抛出呢,因为在线程里不允许throws抛出
OutputStreamout=null
try{
out=new FileOutputStream("D:\\work\\abc\\1.txt",true);
out.write("helloword".getByte());
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(out!=null){
out.close
}
}catch(IOException e){
e.printStackTrace();
}
}
java.io.InputStream所有字节输入流的超类抽象类
InputStream的构造方法
InputStream in=new DileInputStream("D:\\work\\ab\\1.txt");
方法:
int.data=in.read;写入一个字节
in.close:关闭流
循环写入:
int data=0;
while((data=in.read())!=-1) 当遇到最后一个返回-1
sout((char)data);
使用数组写入:
byte[] bytes=new byte[1024];
int len=0;
while((len=in.read(bytes[]))!=-1){
sout(new String(bytes,v,len));
}
复制文件:
public static void copy_2(File srcFile,File destFile)throw IOException{
//字节输入流
Input Stream in=new FileInputStream(srcFile);
//字节数出流
OutputStream out=new FileOutStream(destFile);
//循环写入
byte[] byte=new byte[1024];//使用数组
int len=0;//记录每次读取几个字节
while((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
}
out.close;
in.close;
}
异常处理:
public static void copy_03(File srcFile,File destFile){
InputStrenm in=null;(扩大作用域范围)
OutputStream out=null;
try{
in=new FileInputStream(srcFile);
out=new FileOutStream(destFile);
byte[] bytes=newbyte[1024];
int len=0;
while((len=in.read(byte))!=-1){
out.write(bytes,0,len);
}
}catch(IOException e){
e.printstachTrace();
}finally{
try{
out.close
}catch(IOException e){
e.printStackTrace();
}finally{
in.close();
}
}
}
java.io.Reader 所有字符输入流
字符输出流:
构造方法:
Reader r=newFileReader("D:\\work\\1.txt");
方法:
r.read()读一个字节
r.read(jj):读取jj数组
应用:(读取数据)
int data=0;
while((data=r.read())!=-1){
sout((char)data);
}r.close
字符写入流:
构造方法:
Write w=new FileWrite("d:\\work\\1.txt",true);
方法:
w.write(100):写入
写入数组:
char[] chs={"a",'b','c','d'};
w.write(chs);
!!!!!w.flush:确认输入要不写不进去
w.write(chs,0,3);数组[0,2]
w.write("你好");
java.util.Properties
特点:
1.继承Hashtable实现了Map接口
2.没有泛型键和值都是String类型 ,不允许出现null
3.可以和IO结合使用
方法:
String SetProperty(String key.String value);
String getProperty(object key);
set String PropertyNames();
构造方法:
Properties p =new Properties();
方法:
p.setProperty("name","liuyan");
p.setProperty("age","38");
Set<String> s=P.StringPropertyNames();\\获取所有name
\\将文件中的键值对写入:
Reader r=new FileReader("day20\\Person.txt");\\相对路径从
p.load(r);