The question about how to read and write TXT files in Java is often asked during the interview. Do not understand or be unfamiliar with the comrades, but remember it! Let's take a look at the specific implementation!
Package common;
Import java. Io .*;
Import java. util. arraylist;
Public class iotest {
Public static void main (string ARGs []) {
Readdate ();
Writedate ();
}
/**
* Read data
*/
Public static void readdate (){
String url = "E:/2.txt ";
Try {
Filereader READ = new filereader (new file (URL ));
Stringbuffer sb = new stringbuffer ();
Char ch [] = new char [1024];
Int d = read. Read (CH );
While (D! =-1 ){
String STR = new string (CH, 0, d );
SB. append (STR );
D = read. Read (CH );
}
System. Out. Print (sb. tostring ());
} Catch (filenotfoundexception e ){
E. printstacktrace ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
/**
* Write data
*/
Public static void writedate (){
Try {
File file = new file ("D:/abc.txt ");
If (file. exists ()){
File. Delete ();
}
File. createnewfile ();
Bufferedwriter output = new bufferedwriter (New filewriter (File ));
Arraylist resolvelist = new arraylist ();
For (INT I = 0; I <10; I ++ ){
Resolvelist. Add (math. Random () * 100 );
}
For (INT I = 0; I
Output. Write (string. valueof (resolvelist. Get (I) + "\ n ");
}
Output. Close ();
} Catch (exception ex ){
System. Out. println (Ex );
}
}
}
Original text from [than the Internet], reproduced Please retain the original link: http://soft.chinabyte.com/database/303/12439303.shtml