【JAVA生成各种文件工具】
- 日常工作或者学习中,需要用java生成文本文件,所以就有了下面的代码:
public class FileUtil {
public static File createTxtFile(List<String> dataList,String path,String fileName,String fileType){
File txtFile = null;
BufferedWriter txtWriter = null;
try {
txtFile = new File(path+File.separator+fileName+fileType);
File parent = txtFile.getParentFile();
if (parent!=null && !parent.exists()){
parent.mkdir();
}
txtFile.createNewFile();
// txtWriter = new BufferedWriter(new FileWriter(txtFile));
txtWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(txtFile), CharsetUtil.CHARSET_UTF_8),1024);
for (String row: dataList){
txtWriter.write(row+"
");
}
txtWriter.flush();
}catch (IOException e){
e.printStackTrace();
}finally {
try {
txtWriter.close();
}catch (Exception e){
e.printStackTrace();
}
}
return txtFile;
}
- 如果只是生成在本地的电脑上,用这个就足够,不用指定编码,生成就是中文 txtWriter = new BufferedWriter(new FileWriter(txtFile));
- 如果生成在linux系统上,需要指定编码,一般情况下都是“UTF-8”,这样观看就不会乱码了 txtWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(txtFile), CharsetUtil.CHARSET_UTF_8),1024);
- 这里createTxtFile(List dataList,String path,String fileName,String fileType)的参数含义分别是文本中的数据、生成文件的路径、生成文件的名称、文件的后缀。
下一篇:
java 三个环境变量的理解
