IO

遍历文件夹

 1 public static List<String> listAllFile(String path){
 2         File file=new File(path);
 3         File[] temp=file.listFiles();
 4         for(File fs:temp){
 5             if(fs.getName().equals("$RECYCLE.BIN")){
 6                 continue;
 7             }
 8             if(fs.isDirectory()){
 9                 listAllFile(fs.getAbsolutePath());
10             }else{
11                 String filename=fs.getName();
12                 if(Pattern.matches(".*jpg$", filename)){
13                     list.add(fs.getAbsolutePath());
14                 }
15             }
16         }
17         return list;
18     }


 复制路径下的所有图片到某位置

 1 package File;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.util.ArrayList;
 7 import java.util.List;
 8 import java.util.Random;
 9 import java.util.regex.Pattern;
10 
11 public class TransferPhoto {
12 
13     private static List<String> list=new ArrayList<>();
14     
15     public static void main(String[] args) {
16         // TODO Auto-generated method stub
17         //输入
18         String inputURL="G:/software/YJHAS";
19         //输出
20         String outputURL="F://photo";
21         listAllFile(inputURL);
22         File file=new File(outputURL);
23         file.mkdirs();
24         int lenght=list.size();
25         int jindu=lenght/100;
26         int count=1;
27         for(String str:list){
28             copyPhoto(str,outputURL);
29             count++;
30             if((count%jindu)==0){
31                 int temp=count/jindu;
32                 if(temp%5==0){
33                 System.out.println("下载到"+temp+"%");
34                 }
35             }
36         }
37         System.out.println("success");
38     }
39     
40     public static List<String> listAllFile(String path){
41         File file=new File(path);
42         File[] temp=file.listFiles();
43         for(File fs:temp){
44             if(fs.getName().equals("$RECYCLE.BIN")){
45                 continue;
46             }
47             if(fs.isDirectory()){
48                 listAllFile(fs.getAbsolutePath());
49             }else{
50                 String filename=fs.getName();
51                 if(Pattern.matches(".*jpg$", filename)||Pattern.matches(".*JPG$", filename)){
52                     list.add(fs.getAbsolutePath());
53                 }
54             }
55         }
56         return list;
57     }
58     
59     public static void copyPhoto(String str,String outputURL){
60                 
61         
62         File file=new File(str);
63         String reg = "[^\u4e00-\u9fa5]";
64         str = str.replaceAll(reg, "");
65         str=str+System.currentTimeMillis()+new Random().nextInt(2000);
66         try{
67         
68         FileInputStream fis=new FileInputStream(file.getAbsolutePath());
69         FileOutputStream fos=new FileOutputStream(outputURL+"/"+str+".jpg");
70         int len=0;
71         byte[] b=new byte[1024];
72         while((len=fis.read(b))!=-1){
73             fos.write(b);
74         }
75         }catch(Exception e){
76             e.printStackTrace();
77         }
78     }
79     
80 }

 



File类的常见方法
1.创建。
boolean createNewFile(); //创建文件
boolean mkdir();创建文件夹
boolean mkdirs();创建多级文件夹。

2.删除。
boolean delete();
void deleteOnExit();在程序退出时删除文件。

3.判断。
boolean canExcute(); 判断是否可执行
boolean exists(); 文件事是否存在。
isFile();文件
isDirectory();文件夹
isHidden();//java能得到文件中的隐藏文件但是对隐藏文件时不能访问的
isAbsolute();//绝对路径即时不存在也能得到。
4.获取信息。
getName();
getPath();
getParent();

 getAbsolutePath(); 
 long lastModified(); 
 long length(); 

java.io.File类用于表示文件或目录。
File类只用于表示目标文件(目录)的大小,名称,路径,并可进行是否存在的判断,还有创建和修改等,不能用于文件内容的访问
创建File对象:
File file = new File("E:/...");//文件/文件夹路径对象
File file = new File("..." ,""...);//父目录绝对路径 + 子目录名称
File file = new File("...","...");//父目录File对象 + 子目录名称

file.exists():判断文件/文件夹是否存在
file.delete():删除文件/文件夹
file.isDirectory():判读是否为目录
file.isFile():判读是否为文件夹
file.mkdir():创建文件夹(仅限一级目录)
file.mkdirs():创建多及目录文件夹(包括但不限一级目录)
file.createNewFile():创建文件
file.getAbsolutePath():得到文件/文件夹的绝对路径
file.getName():得到文件/文件夹的名字
file.String():同样是得到文件/文件夹的绝对路径等于file.getAbsolutePath()
file.getParent():得到父目录的绝对路径

String[] gdir.list():得到目录的子目录\文件的名称(不是绝对路径)
File[] dir.listFiles():得到目录的子目录\文件事是否存在。

File.createNewfile创建文本
File.mkdir创建目录
File.tostring方法打印文件全路径名称
File.list列出文件直接子目录或文件的名字
File.listFile列出直接子File对象

 



 流

字节流

 

 字符流

 

byteArrayInputStream和byteArrayOutputStream

 1 /**
 2      * ByteArrayOutputStream
 3      * @author SiyyaWu
 4      */
 5     public static void test1(){
 6         int LEN=5;
 7         byte[] ArrayLetters = {
 8                 0x61, 0x62, 0x63, 0x64, 0x65, 
 9                 0x66, 0x67, 0x68, 0x69, 0x6A, 
10                 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
11                 0x70, 0x71, 0x72, 0x73, 0x74, 
12                 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
13         };
14         ByteArrayInputStream bais = new ByteArrayInputStream(ArrayLetters);
15         for (int i=0; i<LEN; i++) {
16             // 若能继续读取下一个字节,则读取下一个字节
17             if (bais.available() >= 0) {
18                 // 读取“字节流的下一个字节”
19                 int tmp = bais.read();
20                 System.out.printf("%d : 0x%s\n", i, Integer.toHexString(tmp));
21             }
22         }
23 
24         // 若“该字节流”不支持标记功能,则直接退出
25         if (!bais.markSupported()) {
26             System.out.println("make not supported!");
27             return ;
28         }
29         //        System.out.println("skip");
30 
31 
32         //        bais.skip(5);
33         //        byte[] buf = new byte[LEN];
34         //        bais.read(buf, 0, LEN);
35         //        for(int i=0;i<LEN;i++){
36         //            int temp=buf[i];
37         //            System.out.printf("%d : 0x%s\n", i,Integer.toHexString(temp));
38         //        }
39 
40         //标记
41         bais.mark(0);
42         int temp = bais.read();
43         System.out.printf("0x%s\n",Integer.toHexString(temp));
44         //回退到标记位
45         bais.reset();
46 
47         int temp1 = bais.read();
48         System.out.printf("0x%s\n",Integer.toHexString(temp1));
49 
50         bais.reset();
51 
52 
53         //read函数重载
54         byte[] buf = new byte[LEN];
55         bais.read(buf, 0, LEN);
56         for(int i=0;i<LEN;i++){
57             int temp2=buf[i];
58             System.out.printf("%d : 0x%s\n", i,Integer.toHexString(temp2));
59         }
60     }
61     
62     
63     /**
64      * ByteArrayOutputStream
65      * @author SiyyaWu
66      * @throws Exception
67      */
68     public static void test2() throws Exception{
69         byte[] ArrayLetters = {
70                         0x61, 0x62, 0x63, 0x64, 0x65, 
71                         0x66, 0x67, 0x68, 0x69, 0x6A, 
72                         0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
73                         0x70, 0x71, 0x72, 0x73, 0x74, 
74                         0x75, 0x76, 0x77, 0x78, 0x79, 0x7A
75                     };
76         
77         ByteArrayOutputStream baos = new ByteArrayOutputStream();
78         baos.write(0x41);
79         baos.write(0x42);
80         baos.write(0x43);
81         System.out.printf("baos=%s\n", baos);
82     }

 


 

FileInputStream和FileOutputStream

 1 //可以读取中文,但是可能出现乱码
 2     public static void inputStreamRead() throws Exception{
 3         long startTime=System.currentTimeMillis();
 4         File file=new File("D://inputstream.txt");
 5         FileInputStream inputStream=new FileInputStream(file);
 6         int length=0;
 7         byte[] buf=new byte[9];
 8         while((length=inputStream.read(buf))!=-1){
 9             System.out.println(new String(buf,0,length));
10         }
11         inputStream.close();
12         long endTime=System.currentTimeMillis();
13         System.out.println("经历了"+(endTime-startTime)+"ms");
14     }
15     
16     
17     //可以写中文,不出现乱码
18     public static void outputStreamWrite() throws Exception{
19         File file=new File("D://outputStream.txt");
20         FileOutputStream fileOutputStream=new FileOutputStream(file,true);
21         String data="你好";
22         byte[] buf=data.getBytes();
23         fileOutputStream.write(buf,0,buf.length);
24         fileOutputStream.close();
25     }

对于inputStreaml来说,读出的数据是一个一个字节,当读中文时,会出现乱码。使用byte数组读取的话,则由于文本中中英混杂,到处有可能出现乱码。比如byte[] buf=new byte[10] 能接受5哥汉字,但如果汉字中夹有英文,则出现乱码,如“w我的世界中”。

 

FileReader只能一个个读取,不能读取一行。所以我们最常用的读取中英文文本的方法是使用InputStreamReader进行解码,如下

 1 public static String bufferedReader(){
 2         String str=null;
 3         String temp=null;
 4         try {
 5             InputStreamReader isr=new InputStreamReader(new FileInputStream(new File("D://input.txt")),"utf-8");
 6             BufferedReader br=new BufferedReader(isr);
 7             
 8             while((temp=br.readLine())!=null){
 9                 str+=temp+'\n';
10             }
11         } catch (FileNotFoundException e) {
12             // TODO Auto-generated catch block
13             e.printStackTrace();
14         }catch (Exception e) {
15             // TODO: handle exception
16         }
17         return str;
18     }
19     
20     public static void bufferedWriter(){
21         try {
22             OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream(new File("E://abb.txt")),"utf-8");
23             String str=bufferedReader();
24             BufferedWriter bw=new BufferedWriter(osw);
25             bw.write(str);
26             System.out.println("success");
27         } catch (Exception e) {
28             // TODO: handle exception
29         }
30     }

 

posted @ 2019-05-20 23:45  人类一思考上帝就发笑  阅读(218)  评论(0编辑  收藏  举报