java中关于文本文件的读写方法实例总结

时间:2021-05-19

本文实例总结了java中关于文本文件的读写方法。分享给大家供大家参考,具体如下:

写文本数据

方法 一:

import java.io.*;public class A { public static void main(String args[]) { FileOutputStream out; PrintStream ps; try { out = new FileOutputStream("a.txt"); ps = new PrintStream(out); ps.println("qun qun."); ps.println("fei fei"); ps.close(); } catch (Exception e) { System.out.println(e.toString()); } }}

方法 二:

import java.io.*;public class B { public static void main(String args[]) { FileWriter fw; PrintWriter pw; try { fw = new FileWriter("b.txt"); pw = new PrintWriter(fw); pw.print("qunqu n "); pw.println("feiefi ss"); pw.print("qunqu n "); pw.close(); fw.close(); } catch (IOException e) { System.out.println(e.toString()); } }}

方法三:

import java.io.*;public class C { public static void main(String args[]) { String str_written = "This is a simple example"; try { FileWriter fwriter = new FileWriter("c.txt"); BufferedWriter bfwriter = new BufferedWriter(fwriter); bfwriter.write(str_written, 0, str_written.length()); bfwriter.flush(); bfwriter.close(); } catch (IOException e) { System.out.println(e.toString()); } }}

附注:方法一和方法二,方法三都是在操作文本文件不存在的时候将创建,否则,当覆盖之!

另;方法三

BufferedWriter将文本写入字符输出流,缓冲各个字符,从而提供单个字符、数组和字符串的高效写入。

附:追加写入:

import java.io.*;public class C { public static void main(String args[]) { String str_written = "This is a simple example"; try { FileWriter fwriter = new FileWriter("c.txt", true); BufferedWriter bfwriter = new BufferedWriter(fwriter); bfwriter.newLine(); bfwriter.write(str_written, 0, str_written.length()); bfwriter.flush(); bfwriter.close(); } catch (IOException e) { System.out.println(e.toString()); } }}

读文本数据

方法一:

import java.io.*;public class A { public static void main(String args[]) { try { FileInputStream fstream = new FileInputStream("a.txt"); DataInputStream in = new DataInputStream(fstream); while (in.available() != 0) { String a = in.readLine(); System.out.println(a); System.out.println(a.length()); } in.close(); } catch (Exception e) { System.out.println(e.toString()); } }}

方法二:

import java.io.*;public class B { public static void main(String args[]) { try { FileReader fr = new FileReader("a.txt"); BufferedReader br = new BufferedReader(fr); String str; int count = 0; while ((str = br.readLine()) != null) { count++; System.out.println(count + " : " + str); } br.close(); fr.close(); } catch (Exception e) { System.out.println(e.toString()); } }}

附:方法二的能够高效的实现文本数据的读出

希望本文所述对大家Java程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章