Java FileReader Read File __java

Source: Internet
Author: User
Import java.io.*;

Class  Filereaderdemo
{public
	static void Main (string[] args) throws IOException
	{
		//create a file read stream object , associated with a file with the specified name.
		//To ensure that the file is already present, if it does not exist, an exception

will occur FileNotFoundException
		FileReader fr = new FileReader ("Demo.txt");

		Invokes the Read method that reads the stream object.
		//read (): read one character at a time. And it will read down automatically.
		
		int ch = 0;

		while ((Ch=fr.read ())!=-1)
		{
			System.out.println ((char) ch);
		}
		/* While
		(true)
		{
			int ch = fr.read ();
			if (ch==-1) break
				;
			System.out.println ("ch=" + (char) ch);
		}
		*
		/Fr.close ();
	}


The second way: read by a character array.

Import java.io.*;

Class FileReaderDemo2 
{public
	static void Main (string[] args) throws IOException
	{
		FileReader fr = new F Ilereader ("Demo.txt");		

		Defines an array of characters. Used to store read-to characters.
		//This read (char[]) returns the number of characters read.
		char[] buf = new char[1024];

		int num = 0;
		while ((Num=fr.read (BUF))!=-1)
		{
			System.out.println (new String (Buf,0,num));
		Fr.close ();
	}


———— from "Bi Xiangdong 25 Days"


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.