java随笔记

本文介绍Java NIO中文件的写入、复制及日期的获取方法,包括使用StandardOpenOption进行文件操作,通过LocalDate获取当前年月日,并展示了如何利用ConcurrentMap进行线程安全的实例管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件写入

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方式复制文件

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;
        }
    }
 }

年月日获取

LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();

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

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

并发集合不存在则加入

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

判断不为空

// 判断对象不为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对象是否被某注解注解

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

读取配置文件

读取类似properties格式的文件

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);
       }
	}
}

字符串格式化

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

Buffer流写操作

// 获取字符解码类
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());
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值