Write Java program often encountered to read such as txt or write TXT file, but because to define a lot of variables, often do not remember, every time to check, hereby tidy up, easy to use, convenient understood!
Package edu.thu.keyword.test;Import Java.io.File;Import Java.io.InputStreamReader;Import Java.io.BufferedReader;Import Java.io.BufferedWriter;Import Java.io.FileInputStream;Import Java.io.FileWriter;PublicClassCin_txt {Staticvoid Main (String args[]) {try {Prevents file creation or read failures, catches errors with catch and prints, or can throw/* Read in TXT file */String pathname ="D:\\twitter\\13_9_6\\dataset\\en\\input.txt";Absolute path or relative path can be, here is absolute path, write file when show relative path file filename =New File (pathname);The input to read the above path. TXT file InputStreamReader reader =New InputStreamReader (New FileInputStream (filename));Create an input stream object reader BufferedReader br =New BufferedReader (reader);Create an object that turns the contents of the file into a computer-readable language String line =while (line! = null) {line = Br.readline (); //reads one row of data at a time} /* write TXT file */file Writename = new File (//relative path, if not, create a new output. TXT file writename.createnewfile (); //Create new file BufferedWriter out = new bufferedwriter (new FileWriter (Writename)); Out.write ( "I will write to the file \ r \ n"); //\ r \ n is the newline Out.flush (); //the buffer contents into the file Out.close (); //finally remember to close the file} catch (Exception e) {e.printstacktrace ();}} }
Java read-write TXT file