java IO以追加方式写文件FileWrite

package com.demo.test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFile {
/**
* fileName文件名不带扩展名
* content写入内容
* head CSV表头
* @param fileName
* @param content
* @param head
*/
public static void write(String fileName, String content, String head) {
String dirPath = null;
File dirFile = null;
File file = null;
FileWriter fw=null;
BufferedWriter bw=null;
try {
dirPath = System.getProperty("user.dir") + File.separator
+ "N2510data";
dirFile = new File(dirPath);
if(!dirFile.exists()){
dirFile.mkdirs();
System.out.println(dirFile.getAbsolutePath()+"N2510data文件夹创建成功...");
}
file = new File(dirFile, fileName + ".csv");
if (file.exists()) {
if (file.length() > 1024 * 100) {
File destFile = new File(dirFile, fileName + "-"+ System.currentTimeMillis() + ".csv");
file.renameTo(destFile);
WriteFile.createFileAndWriteHead(file, head);
}
}else{
WriteFile.createFileAndWriteHead(file, head);
}
fw = new FileWriter(file, true);
bw = new BufferedWriter(fw);
bw.write(content);
bw.newLine();
bw.flush();
bw.close();

} catch (IOException e) {
e.printStackTrace();
}finally{
bw=null;
fw=null;
}

}

/**
* 创建文件并写入表头
* @param file
* @param head
*/
public static void createFileAndWriteHead(File file, String head) {
FileWriter fw=null;
BufferedWriter bw=null;
try {
if (!file.exists()) {
if (file.createNewFile()) {
fw = new FileWriter(file, true);
bw = new BufferedWriter(fw);
bw.write(head);
bw.newLine();
bw.flush();
bw.close();
} else {
System.out.println("When you create file has error...");
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
bw=null;
fw=null;
}
}

public static void main(String args[]) {
while (true) {
int i = 0;
WriteFile.write("ff", "1000000000000000000000000000000000000",
"001,002,003");
i++;
if (i > 100000) {
break;
}
}
}

}
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页