作者:LoveEmperor-王子様
Java 写入TXT文件,读取TXT文件
如果TXT有乱码,请检查编译器的编码设置,某个文件的编码设置,然后重启
输入写入参数需要修改为字符串,然后传参,这里是外部数据调用写TXT文件
public class TxtExport {
private static String path = "D:/";
private static String filenameTemp;
public static void main(String[] args) throws IOException {
// TxtExport.creatTxtFile();
// TxtExport.writeTxtFile("TXT文件TXT文件TXT文件");
// String res = readTxtFunc(filenameTemp);
}
public static boolean doTxtExportFunc(List<AuthSysLogsDto> vo)throws IOException{
boolean Bool = TxtExport.creatTxtFile();
boolean writeBool = false;
if (Bool){
writeBool = TxtExport.writeTxtFile(vo);
}
// String res = readTxtFunc(filenameTemp);
return writeBool;
}
/**
* 创建文件
*
* @throws IOException
*/
public static boolean creatTxtFile() throws IOException {
boolean flag = false;
Calendar now = Calendar.getInstance();
filenameTemp = path + "DHTGMIS_"+now.get(Calendar.YEAR)+ (now.get(Calendar.MONTH) + 1)
+ now.get(Calendar.DAY_OF_MONTH)+".txt";
File filename = new File(filenameTemp);
if (!filename.exists()) {
filename.createNewFile();
flag = true;
}
return flag;
}
/**
* 写文件
*
* @param vo
* 新内容
* @throws IOException
*/
public static boolean writeTxtFile(List<AuthSysLogsDto> vo) throws IOException {
// 先读取原有文件内容,然后进行写入操作
boolean flag = false;
File readFile=new File(filenameTemp);
String encoding="Unicode"; //字符编码
OutputStreamWriter tofile = new OutputStreamWriter(new FileOutputStream(readFile),"GBK");
BufferedWriter out=new BufferedWriter(tofile);
try {
JSONArray json = JSONArray.fromObject(vo);
// JSONObject jsonObject = JSONObject.fromObject(vo);
byte data[] = json.toString().getBytes();
out.write(new String(data,"GBK"));
flag = true;
}catch (Exception e){
e.printStackTrace();
}
out.flush();
out.close();
return flag;
}
public static String readTxtFunc(String fileName){
String fileContent = "";
try
{
File f = new File(fileName);
if(f.isFile()&&f.exists())
{
InputStreamReader read = new InputStreamReader(new FileInputStream(f),"UTF-8");
BufferedReader reader=new BufferedReader(read);
String line;
while ((line = reader.readLine()) != null)
{
fileContent += line;
}
read.close();
}
} catch (Exception e)
{
e.printStackTrace();
}
System.out.print(fileContent);
return fileContent;
}
}