Java: how to read and write TXT file code l

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.