java創建TXT文件,並寫入數據

public class MyFile {
private static String path = "D:/";
private static String filenameTemp;

/**
* 創建文件
*
* @throws IOException
*/
public static boolean creatTxtFile(String name) throws IOException {
boolean flag = false;
filenameTemp = path + name + ".txt";
File filename = new File(filenameTemp);
if (!filename.exists()) {
filename.createNewFile();
flag = true;
}
return flag;
}

/**
* 寫文件
*
* @param newStr
* 新內容
* @throws IOException
*/
public static boolean writeTxtFile (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(filenameTemp);
// 將文件讀入輸入流
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) {
// TODO 自動生成 catch 塊
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;
}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章