Read the contents of a string in the file, two methods

Source: Internet
Author: User

Method one: With Pushbackreader, a buffer of length 1 is used by default, and the size of the buffer needs to be indicated when creating an object.

public static void Function1 (File f) throws Ioexception{try (Pushbackreader PR = new Pushbackreader (new FileReader (f), 64)) {char[] cbuf = new CHAR[32]; String lastcontent = ""; String content = ""; int hasread = 0;while ((Hasread = Pr.read (cbuf)) > 0) {content = new String (cbuf, 0, hasread); int tar Get = (lastcontent + content). IndexOf ("New Pushbackreader"), if (Target > 0) {pr.unread ((lastcontent + content). ToCharArray ()); if (target > +) {cbuf = new Char[target];p r.read (cbuf, 0, Target); System.out.println (New String (cbuf, 0, Target); break;}} Else{system.out.print (lastcontent); lastcontent = Content;}}}}

Method Two: Using BufferedReader, this class has a ReadLine method, which can read the text in one line, this method is relatively simple.

public static void Function2 (File f) throws Ioexception{try (BufferedReader br = new BufferedReader (new FileReader (f))) { String line = ""; int target = 0;while (line = Br.readline ())!=null) {if (target = Line.indexof ("New BufferedReader") > 0) {System.out.println (line.substring (0, target)); Else{system.out.println (line);}}}

Read the contents of a string in the file, two methods

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.