java.io常见流/java.io.file文件操作大全

http://wosyingjun.iteye.com/blog/1885786

今天学习了下java的IO流,这里做个总结,方便查找。

 

InputStream/OutputSrteam

InputStream是个抽象类,表示字节输入流的所有类的超类。常见的有向文件写入数据。

OutputStream是个抽象类,表示字节输出流的所有类的超类。常见的有从文件写出数据。

继承关系:




  





 

举例:采用FileInputStream/FileOutputStream读写文件。

 

Java代码   收藏代码
  1. package yingjun.io;  
  2.   
  3. import java.io.*;  
  4. //读取文件  
  5. public class TestFileInputStream {  
  6.   public static void main(String[] args) {  
  7.     FileInputStream in = null;//定义一个输入字节流  
  8.     try {  
  9.       in = new FileInputStream("D:/test/newfilename.txt");  
  10.     } catch (FileNotFoundException e) {  
  11.       System.out.println("找不到指定文件");   
  12.       System.exit(-1);  
  13.     }  
  14.       
  15.     try {  
  16.       long num = 0;  
  17.       int b = 0;  
  18.       while((b=in.read())!=-1){ //不等于-1就说明没有读到结尾  
  19.         System.out.print((char)b); //输出字节  
  20.         num++;  
  21.       }  
  22.       in.close();    
  23.       System.out.println();  
  24.       System.out.println("共读取 "+num+" 字节");  
  25.     } catch (IOException e1) {  
  26.       System.out.println("文件读取错误"); System.exit(-1);  
  27.     }  
  28.   }  
  29. }  

 
 

Java代码   收藏代码
  1. package yingjun.io;  
  2.   
  3. import java.io.*;  
  4. //读出文件并写入另一个文件  
  5. public class TestFileOutputStream {  
  6.   public static void main(String[] args) {  
  7.       int b = 0;  
  8.       FileInputStream in = null;//用于读文件  
  9.       FileOutputStream out = null;//用于向文件写数据  
  10.       try {  
  11.         in = new FileInputStream("D:/test/oldfile.txt");//就像在oldfile这个文件里插入一个管道用于读取里面的内容。  
  12.         out = new FileOutputStream("D:/test/newfile.txt");//就像在newfile这个文件里插入一个管道用于向里面写人内容  
  13.         while((b=in.read())!=-1){  
  14.           out.write(b);  
  15.         }  
  16.         in.close();   
  17.         out.close();  
  18.       } catch (FileNotFoundException e2) {  
  19.         System.out.println("找不到指定文件"); System.exit(-1);  
  20.       } catch (IOException e1) {  
  21.         System.out.println("文件复制错误"); System.exit(-1);  
  22.       }  
  23.       System.out.println("文件已经复制");  
  24.   }  
  25. }  

##################################################################

Reader/Writer

 

Reader用于读取字符的抽象类子类必须实现的方法只有 read(char[], int, int) 和 close()。但是,多数子类将重写此处定义的一些方法,以提供更高的效率和/或其他功能。

 Writer写入字符流的抽象类。子类必须实现的方法仅有 write(char[], int, int)、flush() 和 close()。但是,多数子类将重写此处定义的一些方法,以提供更高的效率和/或其他功能。

 

 

 举例:采用FileReader/FileWriter读写文件。

Java代码   收藏代码
  1. package yingjun.io;  
  2.   
  3. import java.io.*;  
  4. //读取文件  
  5. public class TestFileReader {  
  6.   public static void main(String[] args) {  
  7.     FileReader fr = null;   
  8.     int c = 0;  
  9.     try {  
  10.       fr = new FileReader("D:/test/newfilename.txt");  
  11.       while ((c = fr.read()) != -1) {  
  12.         System.out.print((char)c);  
  13.       }  
  14.       fr.close();  
  15.     } catch (FileNotFoundException e) {  
  16.       System.out.println("找不到指定文件");  
  17.     } catch (IOException e) {  
  18.       System.out.println("出错");  
  19.     }  
  20.   
  21.   }  
  22. }  

 

Java代码   收藏代码
  1. package yingjun.io;  
  2.   
  3. import java.io.*;  
  4. //写入文件  
  5. public class TestFileWriter {  
  6.   public static void main(String[] args) {  
  7.     FileWriter fw = null;  
  8.     try {  
  9.       fw = new FileWriter("D:/test/newfilename.txt");  
  10.       for(int c=0;c<=50000;c++){  
  11.         fw.write(c);//c表示的是unicode编码,50000基本涵盖了所有国家的文字。  
  12.       }  
  13.       fw.close();  
  14.     } catch (IOException e1) {  
  15.         e1.printStackTrace();  
  16.       System.out.println("出错");  
  17.       System.exit(-1);  
  18.     }  
  19.   }  
  20. }  

  ######################################################################## 

                                                                      常见处理流

 ########################################################################



 

1:缓冲流

 

Java代码   收藏代码
  1. package yingjun.io;  
  2.   
  3. import java.io.*;  
  4. public class TestBufferStream2 {  
  5.   //向一个文件里写入数据并且从中读取出  
  6.   public static void main(String[] args) {  
  7.     try {  
  8.       BufferedWriter bw = new BufferedWriter(new FileWriter("D:/test/DateTest.java,true"));//true表示不会删除文件之前所有的内容  
  9.       BufferedReader br = new BufferedReader( new FileReader("D:/test/DateTest.java"));  
  10.       String s = null;  
  11.       for(int i=1;i<=10;i++){  
  12.         s = String.valueOf(Math.random());   
  13.         bw.write(s);  
  14.         bw.newLine();  
  15.       }  
  16.       bw.flush();  
  17.       while((s=br.readLine())!=null){  //BufferReader有缓存区的功能,可以读一行  
  18.         System.out.println(s);  
  19.       }  
  20.       bw.close();   
  21.       br.close();  
  22.     } catch (IOException e) {  
  23.         e.printStackTrace();  
  24.     }  
  25.   }  
  26. }  

 2:转换流

 

 

Java代码   收藏代码
  1. package yingjun.io;  
  2.   
  3. import java.io.*;  
  4. public class TestTransForm2 {  
  5.   public static void main(String args[]) {  
  6.     InputStreamReader isr = new InputStreamReader(System.in);//System.in代表键盘输入流  
  7.     BufferedReader br = new BufferedReader(isr);//在外面再套接一层  
  8.     String s = null;  
  9.     try {  
  10.       s = br.readLine(); //等待键盘输入直到输入一行  
  11.       while(s!=null){  
  12.         if(s.equalsIgnoreCase("exit")) break;   
  13.         System.out.println(s.toUpperCase());  
  14.         s = br.readLine();   
  15.       }  
  16.       br.close();  
  17.     } catch (IOException e) {  
  18.       e.printStackTrace();  
  19.     }  
  20.   }  
  21. }   

 3:数据流

 

 

Java代码   收藏代码
  1. package yingjun.io;  
  2.   
  3. import java.io.*;  
  4. public class TestDataStream {  
  5.   public static void main(String[] args) {  
  6.     ByteArrayOutputStream baos =  new ByteArrayOutputStream(); //定义字节数组流  
  7.     DataOutputStream dos = new DataOutputStream(baos);//套接数据类型流  
  8.     try {  
  9.       dos.writeDouble(Math.random());//写入double类型数据  
  10.       dos.writeBoolean(true);  
  11.       ByteArrayInputStream bais =  new ByteArrayInputStream(baos.toByteArray());  
  12.       System.out.println(bais.available());  
  13.       DataInputStream dis = new DataInputStream(bais);  
  14.       System.out.println(dis.readDouble());//读取double类型数据  
  15.       System.out.println(dis.readBoolean());  
  16.       dos.close();   
  17.       dis.close();  
  18.     } catch (IOException e) {  
  19.       e.printStackTrace();  
  20.     }  
  21.   }  
  22. }  

  4:打印流

 

 

Java代码   收藏代码
  1. package yingjun.io;  
  2.   
  3. import java.io.*;  
  4. public class TestPrintStream1 {   
  5.   public static void main(String[] args) {  
  6.     PrintStream ps = null;  
  7.     try {  
  8.       FileOutputStream fos =  new FileOutputStream("D:/test/DateTest.java");  
  9.       ps = new PrintStream(fos);  
  10.     } catch (IOException e) {  
  11.       e.printStackTrace();  
  12.     }  
  13.     if(ps != null){  
  14.       System.setOut(ps);//设定System.out输出到ps(原来是在dos)  
  15.     }  
  16.     for(char c = 0; c <= 60000; c++){  
  17.       System.out.print(c+ " ");//print具有自动的flush功能,所有数据将被写入文件  
  18.     }  
  19.   }  
  20. }  

 

Java代码   收藏代码
  1. package yingjun.io;  
  2.   
  3. import java.text.SimpleDateFormat;  
  4. import java.util.*;   
  5. import java.io.*;  
  6. //类似log功能  
  7. public class TestPrintStream3 {  
  8.   public static void main(String[] args) {  
  9.     String s = null;  
  10.     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
  11.     try {  
  12.       FileWriter fw = new FileWriter ("D:/test/log.java"true);//log   
  13.       PrintWriter log = new PrintWriter(fw);  
  14.       while ((s = br.readLine())!=null) {  
  15.         if(s.equalsIgnoreCase("exit")) break;  
  16.         System.out.println(s.toUpperCase());  
  17.         log.println("-----");  
  18.         log.println(s.toUpperCase());   
  19.         //log.flush();  
  20.       }  
  21.       log.println("==="+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())+"===");   
  22.       log.flush();  
  23.       log.close();  
  24.     } catch (IOException e) {  
  25.       e.printStackTrace();  
  26.     }  
  27.   }  
  28. }  

 5:对象流

 

Java代码   收藏代码
  1. package yingjun.io;  
  2.   
  3. import java.io.*;  
  4.   
  5. public class TestObjectIO {  
  6.     public static void main(String args[]) throws Exception {  
  7.         T t = new T();  
  8.         t.k = 111;  
  9.         FileOutputStream fos = new FileOutputStream("D:/test/DateTest.java");  
  10.         ObjectOutputStream oos = new ObjectOutputStream(fos);  
  11.         oos.writeObject(t);  
  12.         oos.flush();  
  13.         oos.close();  
  14.         FileInputStream fis = new FileInputStream("D:/test/DateTest.java");  
  15.         ObjectInputStream ois = new ObjectInputStream(fis);  
  16.         T tReaded = (T)ois.readObject();  
  17.         System.out.println(tReaded.i + " " + tReaded.j + " " + tReaded.d + " " + tReaded.k);  
  18.     }  
  19. }  
  20.   
  21. class T implements Serializable //可以被序列化的(可以把对象写到文件或者网络上传输)  
  22. {  
  23.     int i = 10;  
  24.     int j = 9;  
  25.     double d = 2.3;  
  26.     transient int k = 15//transient修饰的成员变量在序列化的时候不考虑  
  27. }  

 

==================================================================================================

http://wosyingjun.iteye.com/blog/1885404

java.io.file文件操作大全


Java代码   收藏代码
  1. package yingjun.file;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7.   
  8.   
  9. import org.junit.Test;  
  10.   
  11. public class TestFile {  
  12.       
  13.       
  14.     //创建文件、文件夹  
  15.     @Test  
  16.     public void addFile() throws IOException{  
  17.         //File file=new File("D:/test/testfile/"+"filename.txt");    
  18.         File file=new File("D:/test/testfile/","filename.txt");  
  19.         if(!file.getParentFile().exists()){ //如果该文件路径不存在就创建该路径  
  20.             file.getParentFile().mkdirs();  
  21.         }  
  22.         if(!file.exists()) {  //指定路径下的filename.txt文件要是不存在就创建  
  23.             file.createNewFile();   
  24.         }  
  25.     }  
  26.       
  27.       
  28.       
  29.     //删除文件  
  30.     @Test  
  31.     public void deleteFile(){  
  32.          File file=new File("D:/test/testfile/"+"filename.txt");    
  33.           if(file.exists()&&file.isFile())    
  34.               file.delete();    
  35.     }  
  36.       
  37.       
  38.       
  39.     //删除文件目录  
  40.     @Test  
  41.     public void deleteFileDir(){  
  42.         RecursionDel("D:/test/"); //采用递归删除test目录下的的所有文件(包括test)  
  43.     }  
  44.       
  45.     private void RecursionDel(String path){  
  46.          File dir=new File(path);   
  47.             if(dir.exists()){    
  48.                 File[] tmp=dir.listFiles();    
  49.                 for(int i=0;i<tmp.length;i++){    
  50.                     if(tmp[i].isDirectory()){    
  51.                         RecursionDel("D:/test/"+tmp[i].getName());    
  52.                     }else{    
  53.                         tmp[i].delete();  
  54.                     }    
  55.                 }    
  56.                 dir.delete();    
  57.             }    
  58.     }  
  59.       
  60.       
  61.     //复制文件  
  62.     @Test  
  63.     public void copyFile() throws IOException{  
  64.             FileInputStream in=new FileInputStream("D:/test/testfile/filename.txt");  //要拷贝的文件目录  
  65.             File file=new File("D:/test/filename.txt");  //拷贝到的文件目录  
  66.             if(!file.exists()) {  
  67.                 file.createNewFile();    
  68.             }  
  69.             FileOutputStream out=new FileOutputStream(file);    
  70.             int c;    
  71.             byte buffer[]=new byte[1024];    
  72.             while((c=in.read(buffer))!=-1){    
  73.                 for(int i=0;i<c;i++)    
  74.                     out.write(buffer[i]);            
  75.             }    
  76.             in.close();    
  77.             out.close();    
  78.     }  
  79.       
  80.     //剪切文件  
  81.     @Test  
  82.     public void copyFileDir() throws IOException{  
  83.          File oldfold=new File("D:/test/testfile/lala/asd.txt");    
  84.          File newfold=new File("D:/test/asd.txt");    
  85.          Boolean cover=true;//用于判断是否覆盖  
  86.          if(newfold.exists()){   //若在待转移目录下,已经存在待转移文件    
  87.              if(cover){//覆盖    
  88.                  oldfold.renameTo(newfold);    
  89.              }else    
  90.                  System.out.println("在新目录下已经存在");    
  91.          }else{    
  92.              oldfold.renameTo(newfold);    
  93.          }    
  94.     }  
  95.       
  96.       
  97.       
  98.     //文件重命名  
  99.     @Test  
  100.     public void renameFile(){  
  101.      File oldfile=new File("D:/test/filename.txt");    
  102.      File newfile=new File("D:/test/newfilename.txt");    
  103.       if(newfile.exists())//若在该目录下已经有一个文件和新文件名相同,则不允许重命名    
  104.           System.out.println("已经存在!");    
  105.       else{    
  106.           oldfile.renameTo(newfile);    
  107.       }     
  108.     }  
  109.       
  110.       
  111.     //采用递归的方法遍历某个文件夹下的所有文件.  
  112.     @Test  
  113.     public void listFile(){  
  114.         File f = new File("d:/test");  
  115.         fileList(f);  
  116.     }  
  117.       
  118.     private static void fileList(File f) {  
  119.         File[] childs = f.listFiles();  
  120.         for(int i=0; i<childs.length; i++) {  
  121.             if(childs[i].isDirectory()) {  
  122.                 fileList(childs[i]);  
  123.             }else{  
  124.                 System.out.println(childs[i].getAbsolutePath());  
  125.             }  
  126.         }  
  127.     }  
  128.   
  129.       
  130.       
  131.       



  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值