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!
Packageedu.thu.keyword.test;ImportJava.io.File;ImportJava.io.InputStreamReader;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.FileInputStream;ImportJava.io.FileWriter; Public classCin_txt {Static voidMain (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 or relative path, this is an absolute path, and a relative path is shown when writing to a fileFile filename =NewFile (pathname);//the input to read the above path. TXT fileInputStreamReader reader =NewInputStreamReader (NewFileInputStream (filename));//Create an input stream object readerBufferedReader br =NewBufferedReader (reader);//create an object that turns the contents of a file into a language that the computer can readString line = ""; Line=Br.readline (); while(Line! =NULL) { line= Br.readline ();//read one row of data at a time } /*Write TXT file*/File Writename=NewFile (". \\result\\en\\output.txt");//relative path, if not, to create a new output. TXT fileWritename.createnewfile ();//Create a new fileBufferedWriter out =NewBufferedWriter (NewFileWriter (writename)); Out.write ("I will write the file \ r \ n");//\ r \ n is the line breakOut.flush ();//press the buffer contents into the fileOut.close ();//Finally, remember to close the file } Catch(Exception e) {e.printstacktrace (); } }}
See also: http://blog.csdn.net/monkeyduck/article/details/11525771
Java read txt file and write TXT file