A simple implementation of Java for reading files
- 2020-04-01 03:27:55
- OfStack
This article illustrates a simple and useful way to implement Java reading files. Share with you for your reference. Specific methods are as follows:
This is a simple code to read a file, try to read a log file, and then output.
The main code is as follows:
import java.io.*;
public class FileToString {
public static String readFile(String fileName) {
String output = "";
File file = new File(fileName);
if(file.exists()){
if(file.isFile()){
try{
BufferedReader input = new BufferedReader (new FileReader(file));
StringBuffer buffer = new StringBuffer();
String text;
while((text = input.readLine()) != null)
buffer.append(text +"/n");
output = buffer.toString();
}
catch(IOException ioException){
System.err.println("File Error!");
}
}
else if(file.isDirectory()){
String[] dir = file.list();
output += "Directory contents:/n";
for(int i=0; i<dir.length; i++){
output += dir[i] +"/n";
}
}
}
else{
System.err.println("Does not exist!");
}
return output;
}
public static void main (String args[]){
String str = readFile("C:/1.txt");
System.out.print(str);
}
}
The output results are as follows:
Go Olympics!
Go Beijing!
Go China!
Here the FileReader class opens a file, but it doesn't know how to read a file, which requires the BufferedReader class to provide the ability to read text lines. This combines the functionality of the two classes to open and read files. This is a technique for wrapping flow objects by adding services from one stream to another.
It is also important to note that Java accepts both "/" and "/" when opening a file by path, except that when "/" is used, another "/" is escaped.
I hope this article will be helpful to your Java programming study.