生成Csv
程序员文章站
2022-03-15 17:36:56
...
package main.java;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
public class GenerateCsvTest {
private static StringBuilder st = new StringBuilder();
public static void main(String[] args) throws Exception {
String filePath = getExportPath("Test", false);
OutputStreamWriter osw = null;
File exportFile = null;
try {
exportFile = getFile(filePath, "Test");
osw = new OutputStreamWriter(new FileOutputStream(exportFile.getAbsoluteFile()), "UTF-8");
writeFile(osw, "Test");
} catch (Exception e) {
System.out.println("Export failed exception");
e.getStackTrace();
} finally {
osw.close();
exportFile.setReadable(true, false);
}
}
public static void writeFile(OutputStreamWriter osw, String fileName) throws IOException {
osw.write('\uFEFF');
osw.append("NO1,NO2,NO3,NO4,NO5\n");
osw.append("1,2,3,4,5\n");
System.out.println("写入完成!");
System.out.println("文件名:" + getFullFileName(fileName));
}
// Return full Name for name
public static String getFullFileName(String fileName) {
String exportPath = getExportPath(fileName, false);
return exportPath.substring(exportPath.lastIndexOf(File.separatorChar) + 1, exportPath.lastIndexOf(".")).trim();
}
public static String addZeroForNum(String str, int strLength) {
int strLen = str.length();
if (strLen < strLength) {
while (strLen < strLength) {
StringBuffer sb = new StringBuffer();
sb.append("0").append(str);// 左补0
// sb.append(str).append("0");//右补0
str = sb.toString();
strLen = str.length();
}
}
return str;
}
public static String getExportPath(String fileName, boolean isRename) {
Date date = new Date();
String yyyy = new SimpleDateFormat("yyyy").format(date);
String mm = new SimpleDateFormat("MM").format(date);
String dd = new SimpleDateFormat("dd").format(date);
String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(date);
if (isRename == false) {
return yyyy + File.separatorChar + mm + File.separatorChar + dd + File.separatorChar + fileName + "_[" + yyyyMMdd + "].csv";
} else {
return yyyy + File.separatorChar + mm + File.separatorChar + dd + File.separatorChar + fileName + "_[" + yyyyMMdd + "]" + date.getTime()
+ ".csv";
}
}
public static File getFile(String filePath, String fileName) throws Exception {
File file = new File(filePath.substring(0, filePath.lastIndexOf(File.separatorChar)).trim());
if (!file.exists()) {
file.mkdirs();
System.out.println("路径不存在,创建中........");
}
File exportFile = new File(filePath);
if (exportFile.exists()) {
exportFile.renameTo(new File(getExportPath(fileName, true)));
System.out.println("文件存在,更名中....");
}
exportFile.createNewFile();
System.out.println("新文件创建中");
return exportFile;
}
}