常用Java代码示例

list 集合转 list 集合

原始集合转成新的集合,如 DO 转 DTO,伪代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.woodwhales.model.UserDTO
import org.woodwhales.entity.UserDO

public List<UserDTO> getAllUserDTOList() {
return Optional.ofNullable(UserMapper.selectAll())
.orElse(Collections.emptyList())
.stream()
.map(this::do2dto)
.collect(Collectors.toList());
}

private UserDTO do2dto(UserDO userDO) {
Integer userId = userDO.getId;
String userName = userDO.getUserName;

UserDTO userDTO = new UserDTO(userId, userName);

return userDTO;
}

list 字符数据存入文件并压缩打包

使用 apache 的文件压缩包、IO 工具包和通用包:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>

解压缩源码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package org.woodwhales.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveOutputStream;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public Class FileTools {
private final static int BUFFER_SIZE = 8024;

public final static String ZIP_SUFFIX = ".zip";

private final static String ATTACHMENT = "attachment; filename=";

/**
* 将list中的字符串数据压缩到文件后缀为 suffix 的文件中,
* 并对当前列表文件打包成一个zip压缩包
*/
public static byte[] zipToFile(List<String> fileContentList, String suffix) throws IOException, ArchiveException {
ByteArrayOutputStream archiveStream = new ByteArrayOutputStream();
ArchiveOutputStream archive = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.ZIP, archiveStream);

for (String fileContent : fileContentList) {
// 生成文件名一个UUID的文件
ZipArchiveEntry entry = new ZipArchiveEntry(UUID.randomUUID().toString() + suffix);
// 将要打进压缩包的文件放进压缩文件对象中
archive.putArchiveEntry(entry);
InputStream in = IOUtils.toInputStream(fileContent, StandardCharsets.UTF_8);
BufferedInputStream input = new BufferedInputStream(in);
IOUtils.copy(input, archive);
input.close();
archive.closeArchiveEntry();
}
archive.finish();
byte[] byteArray = archiveStream.toByteArray();
archiveStream.close();

return byteArray;
}

public static boolean isZipFile(String originalFilename) {
return StringUtils.endsWith(originalFilename, ZIP_SUFFIX);
}

public static List<String> getZipFileContent(MultipartFile file) {
if (file.isEmpty()) {
return null;
}

List<String> results = null;
try {
results = unZip(file.getInputStream());
} catch (IOException e) {
log.warn("unzip process is filed! cause by : {}", e.getMessage());
e.printStackTrace();
}
return results;
}

public static List<String> getZipFileContent(String zipFile) {
if(StringUtils.isEmpty(zipFile)) {
return null;
}

List<String> results = null;
try {
results = unZip(new FileInputStream(new File(zipFile)));
} catch (FileNotFoundException e) {
log.warn("unzip process is filed! cause by : {}", e.getMessage());
e.printStackTrace();
}
return results;
}

private static List<String> unZip(InputStream zipFile) {
if(zipFile == null) {
return null;
}
// get the zip file content
List<String> lists = null;
ZipInputStream zis = null;
try {
zis = new ZipInputStream(zipFile);
// get the zipped file list entry
ZipEntry ze = zis.getNextEntry();
log.debug("file size = {}", ze.getSize());
lists = new ArrayList<>();
while (ze != null) {
log.debug("file name = {}", ze.getName());
byte[] byteArray = IOUtils.toByteArray(zis);
lists.add(new String(byteArray, StandardCharsets.UTF_8));
ze = zis.getNextEntry();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(zis != null) {
try {
zis.closeEntry();
zis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return lists;
}

public static void compressFiles2Zip(File[] files, String zipFilePath) {
if (files != null && files.length > 0) {
ZipArchiveOutputStream zaos = null;
File f = new File(zipFilePath);
if (f.isDirectory()) {
log.info("this zipFilePath = {} is Directory", zipFilePath);
return;
}

if (f.exists()) {
f.delete();
}

try {
File zipFile = new File(zipFilePath);
zaos = new ZipArchiveOutputStream(zipFile);
zaos.setUseZip64(Zip64Mode.AsNeeded);
// int index = 0;
for (File file : files) {
if (file != null) {
ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file,
new File(file.getParent()).getName() + File.separator + file.getName());
zaos.putArchiveEntry(zipArchiveEntry);
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[BUFFER_SIZE];
int len = -1;
while ((len = is.read(buffer)) != -1) {
// flush buffer into ZipArchiveEntry
zaos.write(buffer, 0, len);
}
// Writes all necessary data for this entry.
zaos.closeArchiveEntry();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (is != null)
is.close();
}
}
}
zaos.finish();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (zaos != null) {
zaos.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}

public static String genAttachment(String fileName) {
StringBuffer sb = new StringBuffer();
sb.append(ATTACHMENT).append(fileName);
return sb.toString();
}

public static String getOriginalFilename(MultipartFile file) {
if (file == null) {
return null;
}
return file.getOriginalFilename();
}

private FileTools() {
}
}

时间日期工具

时间日期使用了 JDK1.8 的Instant

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package org.woodwhales.utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateUtils {

private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

private static final String OFFSETID = "+8";

private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT);

private static final ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat(DEFAULT_DATE_FORMAT);
}
};

public static String format(Long milliSecond) {
if(milliSecond == null || milliSecond <= 0) {
return "";
}
return threadLocal.get().format(milliSecond);
}

public static String format(Date date) {
if(date == null) {
return "";
}
LocalDateTime localDateTime = convertLocalDateTime(date);
Long milliSecond = getMilliSecond(localDateTime);
return format(milliSecond);
}


public static Long getMilliSecond() {
return LocalDateTime.now().toInstant(ZoneOffset.of(OFFSETID)).toEpochMilli();
}

public static Long getMilliSecond(LocalDateTime localDateTime) {
return localDateTime.toInstant(ZoneOffset.of(OFFSETID)).toEpochMilli();
}

public static Instant getInstant() {
Instant instant = LocalDateTime.now().toInstant(ZoneOffset.of(OFFSETID));
return instant;
}

public static Date getNowDate() {
Instant instant = getInstant();
return convertDate(instant);
}

public static String getNowStr() {
Instant instant = getInstant();
return formatter.format(instant);
}

public static String getNowStr(String formatterStr) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatterStr);
return formatter.format(now);
}

public static Instant convertInstant(Date date) {
Instant instant = date.toInstant();
return instant;
}

public static LocalDateTime convertLocalDateTime(String dateStr) {
LocalDateTime localDateTime = LocalDateTime.parse(dateStr, formatter);
return localDateTime;
}

public static LocalDateTime convertLocalDateTime(String dateStr, String formatterStr) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatterStr);
LocalDateTime localDateTime = LocalDateTime.parse(dateStr, formatter);
return localDateTime;
}

public static LocalDateTime convertLocalDateTime(Date date) {
LocalDateTime localDateTime = LocalDateTime.ofInstant(convertInstant(date), ZoneId.systemDefault());
return localDateTime;
}

public static Instant convertInstant(LocalDateTime localDateTime) {
Instant instant = localDateTime.toInstant(ZoneOffset.of(OFFSETID));
return instant;
}

public static Date convertDate(String dateStr) {
LocalDateTime convertLocalDateTime = convertLocalDateTime(dateStr);
Date date = convertDate(convertInstant(convertLocalDateTime));
return date;
}

public static Date convertDate(Instant instant) {
Date date = Date.from(instant);
return date;
}

public static Date convertDate(LocalDateTime localDateTime) {
return Date.from(convertInstant(localDateTime));
}

public static LocalDate convertLocalDate(LocalDateTime localDateTime) {
int year = localDateTime.getYear();
Month month = localDateTime.getMonth();
int day = localDateTime.getDayOfMonth();
LocalDate localDate = LocalDate.of(year, month, day);
return localDate;
}

public static boolean compareDateisAfter(Date date) {
LocalDateTime nowLocalDateTime = convertLocalDateTime(getNowDate());
LocalDateTime compareLocalDateTime = convertLocalDateTime(date);
return compareLocalDateTime.isAfter(nowLocalDateTime);
}

public static boolean compareDateisBefore(Date date) {
return !compareDateisAfter(date);
}

public static Date plusYears(Date date, int years) {
LocalDateTime localDateTime = convertLocalDateTime(date);
return convertDate(localDateTime.plusYears(years));
}

public static Date plusMinutes(Date date, int minutes) {
LocalDateTime localDateTime = convertLocalDateTime(date);
return convertDate(localDateTime.plusMinutes(minutes));
}
}

时间工具类

以下时间工具类主要增加了:between()方法,可以计算两个时间的差值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;

import lombok.Data;

public class DateUtils {

private static ZoneOffset zoneOffset = ZoneOffset.ofHours(8);

private static String zoneId = zoneOffset.getId();

private static ZoneId systemDefaultZoneId = ZoneId.systemDefault();

private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

public static ZoneOffset getDefaultZoneOffset() {
return zoneOffset;
}

public static ZoneId getSystemDefaultZoneId() {
return systemDefaultZoneId;
}

public static ZoneId getDefaultZoneId() {
return ZoneId.of(zoneId);
}

public static Instant getInstant() {
return Instant.now().atZone(zoneOffset).toInstant();
}

public static Instant getInstant(Long epochMilli) {
return Instant.ofEpochMilli(epochMilli);
}

public static Instant getInstant(Date date) {
return date.toInstant();
}

public static Instant getInstant(ZoneId zoneId) {
return Instant.now().atZone(zoneId).toInstant();
}

public static Instant getInstant(LocalDateTime localDateTime, ZoneOffset zoneOffset) {
return localDateTime.toInstant(zoneOffset);
}

public static Instant getInstant(LocalDateTime localDateTime) {
return localDateTime.toInstant(zoneOffset);
}

public static LocalDateTime getLocalDateTime() {
return LocalDateTime.ofInstant(getInstant(), zoneOffset);
}

public static LocalDateTime getLocalDateTime(long epochMilli) {
return getLocalDateTime(getInstant(epochMilli));
}

public static LocalDateTime getLocalDateTime(Instant instant) {
return LocalDateTime.ofInstant(instant, zoneOffset);
}

public static LocalDateTime getLocalDateTime(String dataStr) {
return LocalDateTime.parse(dataStr, formatter);
}

public static LocalDateTime getLocalDateTime(String dataStr, DateTimeFormatter dateTimeFormatter) {
return LocalDateTime.parse(dataStr, dateTimeFormatter);
}

public static String getNowStr() {
return getLocalDateTime().format(formatter);
}

public static String getNowStr(Instant instant) {
return getLocalDateTime(instant).format(formatter);
}

public static String getNowStr(LocalDateTime localDateTime) {
return localDateTime.format(formatter);
}

public static Long toEpochMilli(Instant instant) {
return instant.toEpochMilli();
}

public static MyDuration between(Instant startInstant, Instant endInstant) {
LocalDateTime startLocalDateTime = getLocalDateTime(startInstant);
LocalDateTime endLocalDateTime = getLocalDateTime(endInstant);
return between(startLocalDateTime, endLocalDateTime);
}

public static Date getDate() {
return Date.from(getInstant());
}

public static Date getDate(LocalDateTime localDateTime) {
return Date.from(getInstant(localDateTime));
}

/**
*
* @param startLocalDateTime
* @param endLocalDateTime 要被减的时间日期
* @return
*/
public static MyDuration between(LocalDateTime startLocalDateTime, LocalDateTime endLocalDateTime) {
Duration duration = Duration.between(startLocalDateTime, endLocalDateTime);

long days = duration.toDays();
long hours = duration.toHours();
long minutes = duration.toMinutes();
long seconds = duration.getSeconds();

MyDuration myDuration = new MyDuration();
myDuration.setDiffDays(days);
myDuration.setDiffHours(hours);
myDuration.setDiffMintines(minutes);
myDuration.setDiffSeconds(seconds);

myDuration.setDays(days);

Duration ofDays = Duration.ofDays(days);
long leftHours = hours - ofDays.toHours();

myDuration.setHours(leftHours);
Duration ofHours = Duration.ofHours(leftHours);

long leftMintines = minutes - ofDays.toMinutes() - ofHours.toMinutes();
myDuration.setMintines(leftMintines);

Duration ofMinutes = Duration.ofMinutes(leftMintines);
myDuration.setSeconds(seconds - ofDays.getSeconds() - ofHours.getSeconds() - ofMinutes.getSeconds());
return myDuration;
}

private DateUtils() {}

@Data
public static class MyDuration {

/**
* 以天数为单位的两个日期时间之间的差值
*/
private long diffDays;

/**
* 以小时为单位的两个日期时间之间的差值
*/
private long diffHours;

/**
* 以分钟为单位的两个日期时间之间的差值
*/
private long diffMintines;

/**
* 以秒为单位的两个日期时间之间的差值
*/
private long diffSeconds;

private long days;
private long hours;
private long mintines;
private long seconds;

public boolean isOver(long value, TimeUnit timeUnit) {
if(StringUtils.equals(timeUnit.name(), TimeUnit.DAYS.name())) {
return this.diffDays >= value;
}

if(StringUtils.equals(timeUnit.name(), TimeUnit.HOURS.name())) {
return this.diffHours >= value;
}

if(StringUtils.equals(timeUnit.name(), TimeUnit.MINUTES.name())) {
return this.diffMintines >= value;
}

if(StringUtils.equals(timeUnit.name(), TimeUnit.SECONDS.name())) {
return this.diffSeconds >= value;
}

throw new RuntimeException("timeUnit is not DAYS or HOURS or MINUTES or SECONDS");
}

/**
* 两个时间差的格式化表示
* 如:两个日期时间之差为:2天3小时25分钟30秒
* @return
*/
public String getFormatterString() {
StringBuffer sb = new StringBuffer();
if(this.days != 0L) {
sb.append(days + "天");
}

if(this.hours != 0L) {
sb.append(hours + "小时");
}

if(this.mintines != 0L) {
sb.append(mintines + "分钟");
}

if(this.seconds != 0L) {
sb.append(seconds + "秒");
}
return sb.toString();
}
}
}

参考资料:

对非常大的两个数字求和——数字字符串求和

【算法】大数相乘问题及其高效算法

利用JAVA API函数实现数据的压缩与解压缩

updated updated 2020-03-01 2020-03-01
本文结束感谢阅读

本文标题:常用Java代码示例

本文作者:木鲸鱼

微信公号:木鲸鱼 | woodwhales

原始链接:https://woodwhales.cn/2019/09/28/044/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%