java中關於文本文件的讀寫辦法實例總結。本站提示廣大學習愛好者:(java中關於文本文件的讀寫辦法實例總結)文章只能為提供參考,不一定能成為您想要的結果。以下是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法式設計有所贊助。