本文实例为大家分享了 java 创建 txt 文件并 存入 内容的具体代码,供大家参考,具体内容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
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://blog.csdn.net/u014801403/article/details/70227624
查看更多关于java创建txt文件并存入内容的详细内容...