Java字符串写入服务器并在服务器中生成text类型文件

今天实现一个功能:后台访问各类接口,将接口中的入参、出参、接口名写入一个自定义文件中存到服务器给定的路径中,其中根据日期生成新的文件,文件中根据时间戳进行换行。

package com.example.demo.code.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Administrator
 *
 */
public class TestServiceImpl {

    /**
     * 通过输出流的方式复制内容
     * @param
     * @throws IOException
     */
    public static void fastCopy(String src,String dist){
        try{
            /*获取服务器路径下的文件,若获取不到则自动创建*/
            /*true不覆盖已有内容*/
            FileOutputStream fileOutputStream = new FileOutputStream(dist,true);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String string = simpleDateFormat.format(new Date());
            String string1 = new String();
            string1 = string+"      "+src;
            /*将字符串内容写入到文件中*/
            fileOutputStream.write(string1.getBytes());
            // 写入一个换行
            fileOutputStream.write("\r\n".getBytes());
            fileOutputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     *
     *创建日志文件
     * @param inParam 入参
     * @param outParam 出参
     * @param interfaceName 接口名称
     */
    public static void createLog(String inParam,String outParam,String interfaceName){
        Map map = new HashMap();
        map.put("入参",inParam);
        map.put("出参",outParam);
        map.put("接口名称",interfaceName);
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        /*实例化日期用于生成文件名称*/
        String fileName = simpleDateFormat2.format(new Date()).replaceAll("-","").replaceAll(" ","").replaceAll(":","").substring(0,8);
        /*在相应的路径下创建对应的文件夹*/
        String filePath = "D:/image/yingxiang/"+"log"+fileName+".txt";
        /*调用读取文件写入内容方法*/
        fastCopy(map.toString(),filePath);
    }

    /**
     * 接口调用
     */
    public void sendMessage(){
        String inParam = "123";
        String outParam = "456";
        String interfaceName = "sendMessage";
        /*调用创建日志文件方法*/
        createLog(inParam,outParam,interfaceName);
    }

    /**
     * 主函数
     * @param args
     */
    public static void main(String[] args){
        TestServiceImpl testService = new TestServiceImpl();
        testService.sendMessage();
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值