Reading files The colored, to comment. |
|
/** This program shows how to read a txt file that already exist. To read a txt file, we use mainly two calsses: BufferReader and FileReader: FileReader TheFileToRead = new FileReader (NameOfFile); BufferReader TheInputFile = new BufferReader (TheFileToRead); Or, in one line: BufferReader TheInputFile = new BufferReader(new FileReader (NameOfFile)); To read, we apply the method readLine() to the object TheInputFile of the Java predefined class BufferReader: TheInputFile.readLine(); We use TheInputFile.close(); to close the file. In this program, we can read a file , test whther we have a palindrome, swap, sort and gives the largest palindrome in the file Words.txt. This former is a simple table with a single column; otherwise, we might use substring Java method to locate the related string the long of the line. Author: Abdurrazzak Ajaja, 2007. Version 1.0 */ import java.io.*; //Input and Output stream packages public class ReadFiles { public static void main (String[] args) throws IOException { //The file to read to fetch a plindrome ReadTheFile("C:/Documents and Settings/Ajaja/My Documents/Abder/NewJava/Files/Words.txt"); } static void ReadTheFile (String ThisFile)throws IOException{ BufferedReader Entrance = new BufferedReader(new FileReader (ThisFile)); boolean TheEndOfFile = false; int TheLengthOfWord; int StringMax = Integer.MIN_VALUE;//MIN_VALUE: predefined String TheLargest = null; while(!TheEndOfFile){ String TheLine = Entrance.readLine(); if (TheLine != null){ // System.out.println(TheLine); To uncomment to list the words in the list TheLengthOfWord = TheLine.length(); // the length of the line // System.out.println(TheLengthOfWord); To uncomment if we want //the size (nmber of characters) of the words in the list if(isPalindrome(TheLine) && (TheLengthOfWord > StringMax)){ StringMax = TheLengthOfWord; //swap Integer.parseInt TheLargest = TheLine;} } else TheEndOfFile = true; } Entrance.close(); if(TheLargest != null) System.out.println ("\n\t The largest palindrome in the list is: " + TheLargest); //if we have palindromes else System.out.println("\n\t No palindrome is available in the list.");// if not } static boolean isPalindrome(String s) { // Test if a string is a word int Left = 0; int Right = s.length() - 1; while (Left < Right) { if (s.charAt(Left) != s.charAt(Right)) return false; Left++; Right--; } return true; } }//end of the class ReadFiles BufferReader TheInputFile = new BufferReader(new FileReader (NameOfFile)); |