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;
}
}