This article summarizes the reading and writing methods of text files in Java. Share it for your reference, as follows:
Write text data
Method 1:
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()); } }}
Method 2:
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("qunqun "); pw.println("feifi ss"); pw.print("qunqun "); pw.close(); fw.close(); } catch (IOException e) { System .out.println(e.toString()); } }}
Method 3:
import java.io.*;public class C { public static void main(String args[]) { String str_writen = "This is a simple example"; try { FileWriter fwriter = new FileWriter("c.txt"); BufferedWriter bfwriter = new BufferedWriter(fwriter); bfwriter.write(str_writeten, 0, str_writeten.length()); bfwriter.flush(); bfwriter.close(); } catch (IOExcept ion e) { System.out.println(e.toString ()); } }}
Note: Method 1 and Method 2 and Method 3 are created when the operation text file does not exist, otherwise, it will be overwritten!
Another; Method 3
BufferedWriter writes text to a character output stream, buffering individual characters, thereby providing efficient writing of individual characters, arrays, and strings.
Attachment: Append write:
import java.io.*;public class C { public static void main(String args[]) { String str_writen = "This is a simple example"; try { FileWriter fwriter = new FileWriter("c.txt", true); BufferedWriter bfwriter = new BufferedWriter(fwriter); bfwriter.newLine(); bfwriter.write(str_writeten, 0, str_writeten.length()); bfwriter.flus h(); bfwriter.close(); } catch (IOException e) { System .out.println(e.toString()); } }}
Read text data
Method 1:
import java.io.*;public class A { public static void main(String args[]) { try { FileInputStream fstream = new FileInputStream("a.txt"); DataInputStream i n = 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()); } }}
Method 2:
import java.io.*;public class B { public static void main(String args[]) { try { FileReader fr = new FileReader("a.txt"); BufferedReader br = new Buf feredReader(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()); } }}
Appendix: Method 2 can efficiently realize the reading of text data
I hope this article will be helpful to everyone's Java programming.