前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java 创建txt_java创建txt文件并存入内容

java 创建txt_java创建txt文件并存入内容

作者头像
全栈程序员站长
发布2022-06-24 21:40:17
1.5K0
发布2022-06-24 21:40:17
举报

大家好,又见面了,我是你们的朋友全栈君。

本文实例为大家分享了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;

}

}

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

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/151765.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档