You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Current »

File processing is performed in Java using various classes. The primary class used to handle files is called File. The File class is part of the java.iopackage. 

Example of file processing

As we can see in the following example, there are a lot of classes we need to import to simply read a file, and in addition, we have to handle the exception thrown by some methods. In Python, it is two lines.

File I/O in Java
File dir = new File(".");// get current directory
File fin = new File(dir.getCanonicalPath() + File.separator
				+ "Code.txt");
FileInputStream fis = new FileInputStream(fin);
// Construct the BufferedReader object
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine = null;
while ((aLine = in.readLine()) != null) {
	// Process each line, here we count empty lines
	if (aLine.trim().length() == 0) {
	}
}
// do not forget to close the buffer reader
in.close();
File I/O in Python
myFile = open("/home/xiaoran/Desktop/test.txt")
print myFile.read();
  • No labels