java中关于文本文件的读写方法实例总结
本文实例总结了java中关于文本文件的读写方法。分享给大家供大家参考,具体如下:
写文本数据
方法一:
importjava.io.*; publicclassA{ publicstaticvoidmain(Stringargs[]){ FileOutputStreamout; PrintStreamps; try{ out=newFileOutputStream("a.txt"); ps=newPrintStream(out); ps.println("qunqun."); ps.println("feifei"); ps.close(); }catch(Exceptione){ System.out.println(e.toString()); } } }
方法二:
importjava.io.*; publicclassB{ publicstaticvoidmain(Stringargs[]){ FileWriterfw; PrintWriterpw; try{ fw=newFileWriter("b.txt"); pw=newPrintWriter(fw); pw.print("qunqun"); pw.println("feiefiss"); pw.print("qunqun"); pw.close(); fw.close(); }catch(IOExceptione){ System.out.println(e.toString()); } } }
方法三:
importjava.io.*; publicclassC{ publicstaticvoidmain(Stringargs[]){ Stringstr_written="Thisisasimpleexample"; try{ FileWriterfwriter=newFileWriter("c.txt"); BufferedWriterbfwriter=newBufferedWriter(fwriter); bfwriter.write(str_written,0,str_written.length()); bfwriter.flush(); bfwriter.close(); }catch(IOExceptione){ System.out.println(e.toString()); } } }
附注:方法一和方法二,方法三都是在操作文本文件不存在的时候将创建,否则,当覆盖之!
另;方法三
BufferedWriter将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。
附:追加写入:
importjava.io.*; publicclassC{ publicstaticvoidmain(Stringargs[]){ Stringstr_written="Thisisasimpleexample"; try{ FileWriterfwriter=newFileWriter("c.txt",true); BufferedWriterbfwriter=newBufferedWriter(fwriter); bfwriter.newLine(); bfwriter.write(str_written,0,str_written.length()); bfwriter.flush(); bfwriter.close(); }catch(IOExceptione){ System.out.println(e.toString()); } } }
读文本数据
方法一:
importjava.io.*; publicclassA{ publicstaticvoidmain(Stringargs[]){ try{ FileInputStreamfstream=newFileInputStream("a.txt"); DataInputStreamin=newDataInputStream(fstream); while(in.available()!=0){ Stringa=in.readLine(); System.out.println(a); System.out.println(a.length()); } in.close(); }catch(Exceptione){ System.out.println(e.toString()); } } }
方法二:
importjava.io.*; publicclassB{ publicstaticvoidmain(Stringargs[]){ try{ FileReaderfr=newFileReader("a.txt"); BufferedReaderbr=newBufferedReader(fr); Stringstr; intcount=0; while((str=br.readLine())!=null){ count++; System.out.println(count+":"+str); } br.close(); fr.close(); }catch(Exceptione){ System.out.println(e.toString()); } } }
附:方法二的能够高效的实现文本数据的读出
希望本文所述对大家Java程序设计有所帮助。