Java reads local TXT documents

Source: Internet
Author: User

 

Create a fileinputstream stream mystream for the TXT file, create a bytearrayoutputstream my, and then read mystream and mystream. read (); then write data to my, my. write (); the written data is converted to the array type using tobytearray (). If the TXT document contains Chinese characters, you can use string (data, "gb2312") as the converted array type data ") decodes Chinese characters. Finally, output it to the screen!

Appendix:

Import java. Io .*;

Public class stream

{

Public static void main (string [] ARGs)

{

Try

{

String dirname = "D: // Java work // work zone ";

String myfile = "My java.txt ";

File afile = new file (dirname, myfile );

Inputstream r = new fileinputstream (afile );

Bytearrayoutputstream byteout = new bytearrayoutputstream ();

Byte TMP [] = new byte [256];

Byte context [];

Int I = 0;

While (I = R. Read (TMP ))! =-1)

{

Byteout. Write (TMP );

}

Context = byteout. tobytearray ();

String STR = new string (context, "gb2312"); // decodes Chinese Characters

// Separate rows

String stra [] = Str. Split ("\ n ");

For (INT n = 0; n <stra. length; n ++)

{

System. Out. println (stra [N]);

}

// System. Out. println (STR );

} Catch (exception E)

{

System. Out. println (E); // todo: handle exception

}

}

}

Input from the keyboard:

Code: bufferedreader BR = new bufferedreader (

New inputstreamreader (system. In ));

String myfile = (string) Br. Readline ();

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.