本文章简介是把文件放在本地里面
需求:生成文件,就不让在重新生成文件了。 跟上一篇文章中类似。
package com.xzz.FileText;
import com.xzz.tread.CommonUtil;
import com.xzz.tread.TraceUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
/**
* @ClassName JschTestS
* @Date 20220422
* @Author lcl-xiezezhong
* @Version 1.0
*/
@RestController
@Slf4j
public class JschTestS {
@Autowired
private JSCHTest jschTest;
private static final String NODE_NAME = CommonUtil.getPid();
public final static org.apache.log4j.Logger LOG = Logger.getLogger(JschTestS.class);
@RequestMapping("JSCH")
public void jschTests() throws Exception{
ArrayList<Student> objects = new ArrayList<>();
Student student = new Student();
student.setAge("12");
student.setName("李四");
Student student1 = new Student();
student1.setAge("1216");
student1.setName("张三");
objects.add(student);
objects.add(student1);
System.out.println(objects);
StringBuffer stringBuffer = new StringBuffer();
//java 集合拼接
if (!CollectionUtils.isEmpty(objects)) {
for (int i = 0; i < objects.size(); i++) {
Student student2 = objects.get(i);
stringBuffer.append(student2.getAge()+"|"+student2.getName());
stringBuffer.append("\r\n");
}
}
System.out.println(stringBuffer.toString());
//日期
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
Date date1 = new Date();
String format1 = simpleDateFormat1.format(date1);
//拼接 交易码+File_+日期.txt //创建服务的文件名
String fineName = "DCEP"+"File"+"_"+format1+".txt";
//jschTest.sshSftp(fineName,stringBuffer.toString());
save("D:\\DCEP", fineName, stringBuffer.toString());
}
public void save(String path, String fileName, String Json) throws Exception {
//生成线程号
Thread.currentThread().setName(TraceUtils.getTraceId(NODE_NAME));
LOG.info("保存对账文件内容" + Json);
int ch;
byte[] bytes = new byte[1024];
OutputStream outstream = null;
ByteArrayInputStream inputStream = null;
//path路径
File file = new File(path);
LOG.info("file"+file);
//判断本地文件是否存在
String[] files = file.list();
for (String name : files) {
LOG.info("name"+name);
if (fileName.equals(name)) {
LOG.info("文件" + fileName + "已存在");
}
}
try {
//写入文件
outstream = new FileOutputStream(file.getPath() + File.separator + fileName);
inputStream = new ByteArrayInputStream(Json.getBytes("UTF-8"));
while ((ch = inputStream.read(bytes)) != -1) {
//数据写在文件夹里
outstream.write(bytes, 0, ch);
LOG.info("本地文件创建成功");
}
} catch (Exception e) {
LOG.error("本地创建文件失败");
e.printStackTrace();
} finally {
if (outstream != null) {
outstream.flush();
outstream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}
}
2.看效果
3.引用一下上一篇的最后的结果哈