当前位置: 首页 > news >正文

java相关技术总结

1.操作文件(包含win和linux)
工具类:

package org.example.demo1boot.daran.util;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class FileUtils {



    /**
     * 获取项目路径:拼成全路径
     * linux和window都可以
     * @return
     */
    private static String getProjectTxtPath() {
        String rootPath = System.getProperty("user.dir");  // 项目根目录
        Path txtPath = Paths.get(rootPath, "data", "txt");
        if (!Files.exists(txtPath)) {
            try {
                Files.createDirectories(txtPath);
            } catch (IOException e) {
                throw new RuntimeException("无法创建目录: " + txtPath, e);
            }
        }
        return txtPath.toString();
    }

    /**
     * 写入或者追加文件内容
     * @param data 数据
     * @param fileName 文件名称
     * @param flag true:写入,false:追加
     * @return
     */
    public static String save(String data,String fileName,boolean flag) {
        try {
            String filePath = getProjectTxtPath() + "/"+fileName;
            StandardOpenOption options;
            if(flag){
                options=StandardOpenOption.APPEND;
            }else{
                options= StandardOpenOption.TRUNCATE_EXISTING;
            }
            Files.write(Paths.get(filePath), data.getBytes(),
                    StandardOpenOption.CREATE, options);
            return "数据保存成功: " + filePath;
        } catch (IOException e) {
            return "保存失败: " + e.getMessage();
        }
    }


    //读取文件
    public static String read(String fileName) {
        try {
            String filePath = getProjectTxtPath() + "/"+fileName;
            if (!Files.exists(Paths.get(filePath))) {
                return "文件不存在";
            }
            return new String(Files.readAllBytes(Paths.get(filePath)));
        } catch (IOException e) {
            return "读取失败: " + e.getMessage();
        }
    }
}

调用:

    private static String FILE_NAME = "sensor_data.txt";

    @GetMapping("/saveSensorData")
    public String saveSensorData(@RequestParam String data) {
        if (StringUtils.isEmpty(data)) {
            return "数据不能为空";
        }
        return FileUtils.save(data,FILE_NAME,true);
    }

    @GetMapping("/getSensorData")
    public String getSensorData() {
       return FileUtils.read(FILE_NAME);
    }

相关文章:

  • 在 openEuler 24.03 (LTS) 操作系统上添加 ollama 作为系统服务的步骤
  • 如何在Android系统上单编ko?
  • c++基础知识二
  • 剑指offer经典题目(三)
  • 基于springboot的“协同过滤算法的高考择校推荐系统”的设计与实现(源码+数据库+文档+PPT)
  • 使用模板报错:_G.unicode.len(orgline.text_stripped:gsub(“ “,““))
  • JavaScript保留小数位及提示toFixed未定义
  • 解决文件夹解压中文字符产生乱码的问题
  • SQLI漏洞公开报告分析
  • JS 数组解构
  • 无人机飞控的二次开发,视觉定位
  • 空杯见月,满杯见己
  • 全文 - MLIR Toy Tutorial Chapter 4: 使用 interfaces 开启 通用变换
  • C++怎么调用类中的函数
  • 阿里云CDN应对DDoS攻击策略
  • #苍穹外卖#(个人使用)
  • MyBatis-Plus 的 FieldStrategy 属性
  • 2025年危化品安全管理人员备考指南|智能题库+核心考点解析
  • 工会成立100周年纪念,开发职工健身AI运动小程序、APP方案推荐
  • CDN流量技术详解