java中关于文本文件的读写方法实例总结
本文实例总结了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程序设计有所帮助。
赞 (0)