java創(chuàng)建txt文件并存入內(nèi)容
更新時間:2018年08月15日 08:32:24 作者:韓大帥666
這篇文章主要為大家詳細介紹了java創(chuàng)建txt文件并存入內(nèi)容,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了java創(chuàng)建txt文件并存入內(nèi)容的具體代碼,供大家參考,具體內(nèi)容如下
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 class txtExport { private static String path = "D:/"; private static String filenameTemp; public static void main(String[] args) throws IOException { txtExport.creatTxtFile("你好"); txtExport.writeTxtFile("你好"); } /** * 創(chuàng)建文件 * * @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 * 新內(nèi)容 * @throws IOException */ public static boolean writeTxtFile(String newStr) throws IOException { // 先讀取原有文件內(nèi)容,然后進行寫入操作 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(); // 保存該文件原有的內(nèi)容 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; } }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java實現(xiàn)圖的鄰接表存儲結(jié)構(gòu)的兩種方式及實例應用詳解
這篇文章主要介紹了java實現(xiàn)圖的鄰接表存儲結(jié)構(gòu)的兩種方式及實例應用詳解,鄰接表構(gòu)建圖是必須需要一個Graph對象,也就是圖對象!該對象包含屬性有:頂點數(shù)、邊數(shù)以及圖的頂點集合,需要的朋友可以參考下2019-06-06Java Math類的三個方法ceil,floor,round用法
這篇文章主要介紹了Java Math類的三個方法ceil,floor,round用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07