java创建txt文件,并写入数据,追加数据,数据换行在txt文件里面可以正常显示(\r\n)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public static void main(String[] args) {
//写入文件
try {
creatTxtFile(nextnumber+””,randomballs);
System.out.println(“输出结果到文件成功”);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* java创建txt文件,并写入数据
* @throws IOException
*/
public static boolean creatTxtFile(String fineName,String str) throws IOException {
// System.out.println(“fineName=”+fineName + ” str=”+str);
String path = “F:/kanbox/双色球/上传号码/”;
boolean flag = false;
String fileAddress = path + fineName + “.txt”;
File filename = new File(fileAddress);
if (!filename.exists()) {
filename.createNewFile();
flag = true;
}
writeTxtContent(fileAddress, str);
return flag;
}
/**
* 写文件
* @param str 内容,覆盖掉原来的内容
* @throws IOException
*/
public static boolean writeTxtContent(String fileAddress,String str) throws IOException {
// 先读取原有文件内容,然后进行写入操作
boolean flag = false;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
// 文件路径
File file = new File(fileAddress);
StringBuffer buf = new StringBuffer();
buf.append(str);
fos = new FileOutputStream(file);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
}
return flag;
}
/**
* 写文件
* @param newStr 新内容
* @throws IOException
*/
public static boolean writeTxtFile(String fileAddress,String newStr) throws IOException {
// 先读取原有文件内容,然后进行写入操作
boolean flag = false;
String filein = newStr + “\r\n”;
String temp = “”;
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
// 文件路径
File file = new File(fileAddress);
// 将文件读入输入流
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
// 保存该文件原有的内容
for (int j = 1; (temp = br.readLine()) != null; j++) {
buf = buf.append(temp);
// System.getProperty(“line.separator”)
// 行与行之间的分隔符 相当于“\n”
buf = buf.append(System.getProperty(“line.separator”));
}
buf.append(filein);
fos = new FileOutputStream(file);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return flag;
}
历史上的今天:
- 2015: 2015079期双色球预测(0)
- 上一篇:双色球2014077期预测
- 下一篇:mysql给外部链接用户授权
暂无评论