1 IO流:
1 IO流用来处理设备之间的数据传输
2 Java对数据的操作是通过流的方式。Java用于操作流的对象都封装在IO包中。
3 流按操作数据分为两种:字节流与字符流。流按流向分为:输入流,输出流。
字节流 的抽象基类:Reader Writer
字符流的抽象基类: Inputstream Outputstream
注意:由这四个类派生出来的子类名称都是以其父类名作为子类明的后缀。
2.1字符流
2.1.1
IO流(文本写入)
public static void main(String[] args) {
Writer w=null;
try{ w =new FileWriter("1.Java");
w.write("黑马程序员——新长城");
}
catch(IOException e){
System.out.print("写入失败"+e);
}
finally{
if(w!=null)
try {
w.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.1.2
IO流(文本文件读取方式一)
public static void main(String[] args) {
// TODO Auto-generated method stub
Reader r=null;
try{
r=new FileReader("D:\\1.java");
int ch =0;
while((ch=r.read())!=-1){
System.out.print((char)ch);
}
}
catch(IOException e)
{
System.out.println(e);
}
finally{
if(r!=null)
try {
r.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2.1.3
IO流(文本文件读取方式二public static void main(String[] args) {
// TODO Auto-generated method stub
Reader r=null;
try{
char [] buf=new char[1024];
r=new FileReader("D:\\1.java");
int len =0;
while((len=r.read(buf))!=-1){
//System.out.print((char)ch);
sop(new String(buf,0,len));
}
}
catch(IOException e)
{
System.out.println(e);
}
finally{
if(r!=null)
try {
r.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void sop(Object obj){
System.out.println(obj);
}
2.1.4IO流(拷贝文本文件)
public static void main(String[] args) {
// TODO Auto-generated method stub
Reader r=null;
Writer w=null;
try{
char [] buf=new char[1024];
r=new FileReader("D:\\1.java");
w=new FileWriter("E:\\2.java");
int len =0;
while((len=r.read(buf))!=-1){
w.write(new String(buf,0,len));
//System.out.print((char)ch);
sop(new String(buf,0,len));
}
}
catch(IOException e)
{
System.out.println(e);
}
finally{
if(r!=null)
try {
r.close();
w.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void sop(Object obj){
System.out.println(obj);
}
2.2字符缓冲流
缓冲区的出现提高了对数据的读写效率。在流的基础上对流的功能进行了增强。
对应类。 (1)、BufferedWriter (2)、BufferedReader
2.2.1 O流(通过缓冲区复制文本文件)
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br=null;
BufferedWriter bw=null;
try{
br=new BufferedReader(new FileReader("D://1.java"));
bw=new BufferedWriter(new FileWriter("E://3.java"));
for(String line;(line=br.readLine())!=null;){
bw.write(line);
bw.newLine();
bw.flush();
}
}
catch(IOException e)
{
System.out.println(e);
}
finally{
try{
if(br!=null)
br.close();
}
catch(IOException e){
throw new RuntimeException("读取关闭失败");
}
try{
if(bw!=null)
bw.close();
}
catch(IOException e){
throw new RuntimeException("写入关闭失败");
}
}
}