import java.io.*;
/* 数据库导入命令
load data local infile 'H:\\temp\\data.txt' into table zy_test_t
CHARACTER SET utf8 -- 可选,避免中文乱码问题
FIELDS TERMINATED BY '||' -- 字段分隔符,每个字段(列)以什么字符分隔,默认是 \t
-- ESCAPED BY '\\' -- 转义符,默认是 \
LINES TERMINATED BY '_' -- 记录分隔符,如字段本身也含\n,那么应先去除,否则load data 会误将其视作另一行记录进行导入
(id, str1, str2, str3) -- 每一行文本按顺序对应的表字段,建议不要省略
* */
public class DataInit {
static String columnTerminated = "||"; //列分割符
static String lineTerminated = "_";//行分割符
static String filePath = "H:\\temp\\data.txt";//文件路径
public static void main(String[] args) {
//1.组装字符串
StringBuilder tableValue = new StringBuilder();
for(int i = 0 ;i < 10; i++){
tableValue.append(i);
tableValue.append(columnTerminated);//加入列分割符
tableValue.append("/t");
tableValue.append(columnTerminated);//加入列分割符
tableValue.append("de/t");
tableValue.append(columnTerminated);//加入列分割符
tableValue.append("\\N");//设置为null
tableValue.append(lineTerminated);//加入行分割符
}
//2.写入文件
writeStringToFile(filePath, tableValue.toString());
System.out.println("finish");
}
/**
* 将字符串写入文件(默认UTF-8)
*
* @param path 文件路径
* @param text 字符串
*/
public static void writeStringToFile(String path, String text) {
writeStringToFile(path, text, "UTF-8");
}
/**
* 将字符串写入文件(默认覆盖)
*
* @param path 文件路径
* @param text 字符串
* @param charsetName 编码名称
*/
public static void writeStringToFile(String path, String text, String charsetName) {
File file = new File(path);
writeString(file, false, text, 0, text.length(), charsetName);
}
/**
* 将字符串写入文件
*
* @param file 文件
* @param append 是否追加
* @param text 字符串
* @param off 起始下标
* @param lenght 长度
* @param charsetName 编码名称
*/
public static void writeString(File file, boolean append, String text, int off, int lenght, String charsetName) {
try {
writeString(new FileOutputStream(file, append), text, off, lenght, charsetName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 字符输出流输出字符串
*
* @param os 输出流
* @param text 字符串
* @param off 起始下标
* @param lenght 长度
* @param charsetName 编码
*/
public static void writeString(OutputStream os, String text, int off, int lenght, String charsetName) {
try {
OutputStreamWriter osw = null;
if (charsetName == null) {
osw = new OutputStreamWriter(os);
} else {
osw = new OutputStreamWriter(os, charsetName);
}
BufferedWriter bw = new BufferedWriter(osw);
bw.write(text, off, lenght);
bw.flush();
bw.close();
osw.close();
os.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}