溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java如何創(chuàng)建txt文件并存入內容

發(fā)布時間:2021-06-07 11:35:15 來源:億速云 閱讀:1883 作者:小新 欄目:編程語言

這篇文章將為大家詳細講解有關java如何創(chuàng)建txt文件并存入內容,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

本文實例為大家分享了java創(chuàng)建txt文件并存入內容的具體代碼,供大家參考,具體內容如下

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
 *      新內容
 * @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;
 }
 
}

關于“java如何創(chuàng)建txt文件并存入內容”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI