当前位置: 移动技术网 > IT编程>开发语言>Java > java创建txt文件并存入内容

java创建txt文件并存入内容

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了java创建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("你好");
 }
 
 
 /**
 * 创建文件
 * 
 * @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;
 }
 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网