递归遍历磁盘文件路径、模拟抽奖、线上解析json

匆匆过客 提交于 2020-03-02 21:45:24

今天机试的三个小题目

1、递归遍历磁盘文件路径

使用递归方法,遍历D盘(也可以更换成别的目录,效果达到即可)下全部的文件(包括子文件夹下的文件),输出文件路径,文件修改时间,文件按修改时间倒序排列。

package test;

import java.io.File;
import java.util.*;

/**
 * Created by shimengru on 2020/3/2.
 * 使用递归遍历apache目录下所有文件的文件名
 */

public class ShowFileDir {


    public static void main(String[] args) {
        File file = new File("/Users/admin/Downloads/apache-maven-3.6.2/");
        //校验路径是否为空
        File[] files = file.listFiles();
        if (files == null) {
            System.out.println("请输入正确路径...");
            return;
        }
        File[] fs = seachFileDir(file);//查询后未排序
        //进行排序
        Arrays.sort(fs, new CompareByLastModified());
        //遍历
        for (File f : fs) {
            System.out.println("文件名:" + f.getName());
            System.out.println("文件路径:" + f.getAbsolutePath());
            System.out.println("文件更新时间:" + new Date(f.lastModified()));

        }
    }

    /**
     * 根据更新时间倒序
     */
    static class CompareByLastModified implements Comparator<File> {
        public int compare(File f1, File f2) {
            long diff = f1.lastModified() - f2.lastModified();
            if (diff > 0)
                return -1;
            else if (diff == 0)
                return 0;
            else
                return 1;
        }
    }


    /**
     * 递归查询文件
     */
    public static File[] seachFileDir(File file) {

        // 创建一个空的list
        List<File> fileList = new ArrayList<>();
        File[] files = file.listFiles();
        //遍历根目录
        for (File f : files) {
            if (f.isFile()) {
                // 如果是文件则直接添加到list
                fileList.add(f);
            } else if (f.isDirectory()) {
                // 递归调用
                seachFileDir(f);
            }
        }
        return files;
    }
}




 

2、模拟抽奖

tring s1 = “1,2,3,4,5,6,7,8.9,10,11,12,13,14,15”;//代表全部参与抽奖的人员编号

String s2 =”2,5,6”;//代表已经中奖的人员编号

int number = 3;

写一个函数,从s1中随机筛选出number个数字,且此数字不在s2中。返回一个字符串。

请理解好需求,假设s1是全公司人员编号,s2是一等奖中奖人员,现在是要抽取n个二等奖。

package test;

import java.util.Random;

/**
 * Created by shimengru on 2020/3/2.
 */
public class LotteryDraw {

    public static void main(String[] args) {
        String s1 = "1,2,3,4,5,6,7,8.9,10,11,12,13,14,15";//代表全部参与抽奖的人员编号
        String s2 ="2,5,6";//代表已经中奖的人员编号
        int number = 3;

        String[] s1Array = s1.split(",");
        String[] s2Array = s2.split(",");
        Random r = new Random();
        for (int i = 0; i < number; ) {
            int i1 = r.nextInt(s1Array.length)-1;
            if(!arrayContains(s2Array,s1Array[i1])){
                i++;
                System.out.println(s1Array[i1]);
            }
        }
    }

    /**
     * 查询是否包含
     */
    private static boolean arrayContains(String[] chars,String c){
        for (int i = 0; i < chars.length; i++) {
            if(c.equals(chars[i])) return true;
        }
        return false;
    }
}

3、线上解析json并下载图片

读取并解析json文件: http://123.56.191.196:8080/a/a/d/list_slide_1_0.json,必须是在线读取。把里面的图片下载到本地,并打印出图片文件名和文件大小。

package test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * Created by shimengru on 2020/3/2.
 */
public class ParseJson {

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .connectionPool(new ConnectionPool(10, 60, TimeUnit.SECONDS))
            .retryOnConnectionFailure(true)
            .build();

    public static void main(String[] args) {

        Request request = new Request.Builder()
                .url("http://123.56.191.196:8080/a/a/d/list_slide_1_0.json")
                .get()
                .build();
                //请求URL下载内容
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            String responseText = response.body().string();
            //转为json数组
            JSONArray objects = JSON.parseArray(responseText);
            for (int i = 0; i < objects.size(); i++) {
                JSONObject jsonObject = objects.getJSONObject(i);
                String photoUrl = jsonObject.getString("photo");
                String title = jsonObject.getString("title");
                //下载图片
                downloadPicture(photoUrl, title);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static void downloadPicture(String url, String title) {
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            InputStream inputStream = response.body().byteStream();
            String fileName = "D:\\data\\" + title + ".jpg";
            FileOutputStream outputStream = new FileOutputStream(fileName);
            byte[] data = new byte[1024];
            int i, fileSize = 0;
            while ((i = inputStream.read(data, 0, data.length)) > 0) {
                outputStream.write(data, 0, i);
                fileSize += i;
            }
            System.out.println("文件名:"+fileName);
            System.out.println("文件大小:"+fileSize +"B");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

pom文件



			<dependency>
				<groupId>com.squareup.okhttp3</groupId>
				<artifactId>okhttp-apache</artifactId>
				<version>3.8.1</version>
			</dependency>

			<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpclient</artifactId>
				<version>4.5.6</version>
			</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.56</version>
		</dependency>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!