java随笔记

文件写入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
String fileName = "/root/log/test.log";
Path file = Paths.get(fileName);
boolean exists = Files.exists(Paths.get(dir), LinkOption.NOFOLLOW_LINKS);
try {
if (!exists) {
Files.createDirectories(Paths.get(dir));
}
List<String> lines = Arrays.asList(msg);
// 写文件,CREATE,APPEND打开文件的标志位, 创建或追加
Files.write(file, lines, Charset.forName("UTF-8"),
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
} catch (IOException e) {
LOGGER.info("IOException", e);
}

NIO方式复制文件

1
2
3
4
5
6
7
8
9
10
public static void copyFileByChannel(File source, File dest) throws IOException {
try (FileChannel sourceChannel = new FileInputStream(source).getChannel();
FileChannel targetChannel = new FileOutputStream(dest).getChannel();){
for (long count = sourceChannel.size() ;count>0 ;) {
long transferred = sourceChannel.transferTo(sourceChannel.position(), count, targetChannel);
sourceChannel.position(sourceChannel.position() + transferred);
count -= transferred;
}
}
}

年月日获取

1
2
3
4
LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();

根据配置文件来决定是否显示Swagger

1
2
3
@ConditionalOnExpression("'${swagger.enable}' == 'true'")
public class SwaggerConfig {
}

并发集合不存在则加入

1
2
3
private ConcurrentMap<String, T> singletonInstances = new ConcurrentMap<>();
// 如果不存在此实例则将其放进去
singletonInstances.putIfAbsent(name, instance);

判断不为空

1
2
3
4
5
6
7
8
9
10
11
// 判断对象不为null,如果为null则抛出空指针异常,不为空返回此对象
obj = Objects.requireNonNull(obj);
// 这个是com.google.common.base包中的方法
Preconditions.checkNotNull(url);

// 检查集合不为null,为空抛出空指针
Collections.checkedList(lists)
// 检查map不为空,key或value为空则抛出空指针
Collections.checkedMap(map)
// 检查Set不为空
Collections.checkedSet(set)

检查某个Class对象是否被某注解注解

1
2
// 判断clazz对象是否有MyAnnotation注解
clazz.isAnnotationPresent(MyAnnotation.class);

读取配置文件

读取类似properties格式的文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Enumeration<URL> urls = classLoader.getResources(“META-INF/extensions/test.info”);
if(urls!=null && urls.hasMoreElements()){
while(urls.hasMoreElements()){
URL url = urls.nextElement();
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8"));
String line = null;
while ((line=br.readLine())!=null){
String config = line;
//跳过注释
if(config.startsWith("#")){
continue;
}
String key= null;
String value= null;
int i = config.indexOf('=');
if (i > 0) {
key= config.substring(0, i).trim();
value= config.substring(i + 1).trim();
}
System.out.Println("key:"+key+" value:"+value);
}
}
}

字符串格式化

1
String str = String.format("%s has already been exported", name)

Buffer流写操作

1
2
3
4
5
6
// 获取字符解码类
CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
// 将字符串转换为字节Buffer
ByteBuffer bytes = encoder.encode(CharBuffer.wrap("要写入的值"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("test.txt"));
bos.write(bytes.array(), 0, bytes.limit());
-------------本文结束感谢您的阅读-------------