精选代码

get response body from httpurlconnection

BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}

how-to-get-response-body-using-httpurlconnection-when-code-other-than-2xx-is-re

java mkdir fail 创建文件夹失败 mkdir mkdirs的不同

要注意File.mkdir和File.mkdirs的区别 mkdirs会自动创建父级目录,所以为了避免因为父级目录找不到而导致文件创建失败的情况,应该尽量使用File.mkdirs

参考: https://stackoverflow.com/questions/12126987/java-mkdir-not-writing-directory

文本去重

    public static void main(String[] args) throws Exception {
        String inputFile = "";
        String outputFile = "";
        Charset charset = StandardCharsets.UTF_8;
        try (PrintWriter out = new PrintWriter(outputFile, charset.toString())) {
            StringBuilder text = new StringBuilder();
            try (Stream<String> stream = Files.lines(Paths.get(inputFile),
                    charset)) {
                Map<String, String> check = new HashMap<>();
                stream.forEach(line -> {
                    String value = check.get(line);
                    check.put(line, line);
                    if (null == value) {
                        text.append(line).append("\n");
                    }
                });
            }
            out.println(text);
        }
    }

参考:

how-to-read-a-large-text-file-line-by-line-using-java

how-do-i-save-a-string-to-a-text-file-using-java

从字符串中获取数字

str = str.replaceAll("\\D+","");

参考:

extract digits from a string in java

读取文件夹下所有文件 遍历获取

Java7

public void listFilesForFolder(final File folder) {
    for (final File fileEntry : folder.listFiles()) {
        if (fileEntry.isDirectory()) {
            listFilesForFolder(fileEntry);
        } else {
            System.out.println(fileEntry.getName());
        }
    }
}

final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);

Java8

try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {
    paths
        .filter(Files::isRegularFile)
        .forEach(System.out::println);
} 

参考:how to read all files in a folder from java

文件MD5

        MessageDigest md = MessageDigest.getInstance("MD5");
        try (InputStream is = Files.newInputStream(file.toPath()); 
            DigestInputStream dis = new DigestInputStream(is, md)) {
            final byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
            int read = is.read(buffer, 0, STREAM_BUFFER_LENGTH);

            while (read > -1) {
                md.update(buffer, 0, read);
                read = is.read(buffer, 0, STREAM_BUFFER_LENGTH);
            }
        }
        byte[] data = md.digest();
        StringBuilder r = new StringBuilder(data.length * 2);
        for (byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        // return DatatypeConverter.printHexBinary(data);
        return r.toString();

参照:

getting-a-files-md5-checksum-in-java

how-to-convert-a-byte-array-to-a-hex-string-in-java