本文實(shí)例為大家分享了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)容,然后進(jìn)行寫入操作 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") // 行與行之間的分隔符 相當(dāng)于“/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 自動(dòng)生成 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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選