A small example of Java reading the contents of a file

Source: Internet
Author: User

Java provides the BufferedReader class used to read strings from the stream, and FileReader classes to read files. We use these two classes to read the strings in the file.

Here is an example:

Import Java.io.BufferedReader;
Import Java.io.FileReader;
Import java.io.IOException;
public class readfile{
public static void Main (string[] args) {
String path= "C:/1.txt"; Define file path
String content= ""; Content to save the contents of the file,
BufferedReader Reader=null; Define BufferedReader
try{
Reader=new BufferedReader (new FileReader (path));
Read the file by row and add it to the content.
When the ReadLine method returns NULL, it indicates that the file read completed.
String Line;
while ((Line=reader.readline ())!=null) {
Content+=line+ "n";
}
}catch (IOException e) {
E.printstacktrace ();
}finally{
Finally, close the reader object in finally
if (reader!=null) {
try{
Reader.close ();
}catch (IOException e) {
E.printstacktrace ();
}
}
}
SYSTEM.OUT.PRINTLN ("Document content:" +content);
}
}

We extract the section that reads the file:

public class readfile{
public static void Main (string[] args) {
String path= "C:/1.txt"; Define file path
try{
String content=readfile (path);
SYSTEM.OUT.PRINTLN ("Document content:" +content);
}catch (IOException e) {
E.printstacktrace ();
}
}
/**
* Reads the specified text file and returns the contents
*
* @parampath file path
* @return File contents
* @throwsIOException If the file does not exist, the open fails, or the read fails
*/
private static string ReadFile (string path) throws ioexception{
String content= "";
BufferedReader Reader=null;
try{
Reader=new BufferedReader (new FileReader (path));
String Line;
while ((Line=reader.readline ())!=null) {
Content+=line+ "n";
}
}finally{
if (reader!=null) {
try{
Reader.close ();
}catch (IOException e) {
The exception that appears to turn off reader is generally not handled.
}
}
}
return content;
}
}

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.