The example in this article describes the simple implementation method of reading files in Java, which is very practical. Share it with everyone for your reference. The specific methods are as follows:
This is a simple code that reads a file, and tries to read a log file and then output it.
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 is as follows:
Come on Olympics!
Come on Beijing!
Come on, China!
Here the FileReader class opens a file, but it does not know how to read a file, which requires the BufferedReader class to provide the function of reading lines of text. This requires combining the functions of these two classes to achieve the purpose of opening the file and reading the file. This is a technique for wrapping stream objects, i.e. adding the services of one stream to another stream.
It should also be pointed out that when Java opens a file according to the path, both "/" and "/" are recognized, but when "/" is used, it must be escaped with another "/".
I hope that what this article describes will be helpful to everyone's learning of Java programming.