Java. Examples of implementation of operations that modify text files. Classes FileReader, FileOutputStream, PrintStream

Examples of implementation of operations that modify text files. Classes FileReader, FileOutputStream, PrintStream


Contents


Search other websites:




1. Function CountLinesInFile(). Calculate the number of lines in a character file

The following function can be used to calculate the number of lines in a symbol file

import java.io.*;

...

// Calculate the number of lines in a file
public static int CountLinesInFile(String filename) throws IOException {
  // 1. Delcare internal variables
  int count = 0; // the number of lines in the file - the result
  FileReader fr = null;
  int symbol;

  try {
    // 2. Trying to open a file for reading.
    fr = new FileReader(filename);

    // The cycle of reading characters from a file and counting their number
    do {
      // Read character from file
      symbol = fr.read();

      // Check if there is a line break character
      if ((char)symbol == '\n')
        count++; // Increase the number of lines in the file by 1
    } while (fr.ready()); // Check for end of file
  }
  catch (IOException e)
  {
    // 3. If the file is not open, then display the appropriate message
    System.out.println("I/O error: " + e);
  }
  finally {

    // 4. Close file if it was open
    try {
      if (fr!=null) {
        fr.close();
      }
    }
    catch (IOException e) {
      System.out.println("File close error.");
    }
  }

  // 5. Return the result
  return count;
}

Using a function in other program code may be, for example,

...

public static void main(String[] args) throws IOException {
  // Invoke function CountLinesInFile() для файлу "textFile.txt"
  int count = CountLinesInFile("textFile.txt");
  System.out.println("count = " + count);
}

...

 

2. Function GetLinesFromFile(). Get file lines as an array of strings of type String[]

The following is the GetLinesFromFile() function, which returns an array of strings of a file of type String[]. If there are no lines in the file or an error occurs, the function returns null. This function uses the CountLinesInFile() function (see section 1) to determine the number of lines in a file.

To obtain an array of strings in a function, the means of the FileReader class are used. The function is used in the following examples of this topic.

import java.io.*;

...

// Get the lines of a file as an array of String[]
public static String[] GetLinesFromFile(String filename) throws IOException {
  // 1. Declare internal variables
  int count; // number lines in the file
  String lines[] = null; // array of lines - result
  FileReader fr = null;
  String s; // additional variable - line
  int symbol;
  int i;

  // 2. Get the number of lines in a file - invoke the CountLinesInFile() function
  count = CountLinesInFile(filename);

  // 3. Checking if there are lines in the file
  if (count<=0) return null;

  // 4. Allocate memory for count lines
  lines = new String[count];

  // 5. Reading data from a file and creating an array of lines
  try {
    // 5.1. Trying to open a file for reading.
    fr = new FileReader(filename);

    // 5.2. The cycle of reading characters from a file and creating an array of lines
    s = "";
    i = 0;
    do {
      // Read character from file
      symbol = fr.read();

      // Check for end of line character
      if (((char)symbol == '\n')) {
        // delete from s character '\n'
        s = s.substring(0, s.length()-1);

        // Add string s to array of strings
        lines[i] = s;
        s = "";
        i++; // Increase the number of lines in the file by 1
      }
      else {
        // add a character to a string
        s = s + (char)symbol;
      }
    } while (fr.ready()); // Checking the end of the file
  }
  catch (IOException e) {
    // 5.3. If the file is not open, then display the appropriate message
    System.out.println("I/O error: " + e);
  }
  finally {
    // 5.4. Close file if it was open
    try {
      if (fr!=null) {
        fr.close();
      }
    }
    catch (IOException e) {
      System.out.println("File close error.");
    }
  }

  // 6. Return the result
  return lines;
}

The following is an example of a possible use of the function:

...

public static void main(String[] args) throws IOException {
  // Get the lines of a file as an array (list)
  String lns[];
  lns = GetLinesFromFile("textFile.txt");
  System.out.println("\n\nThe content of file is:");
  for (int i=0; i<lns.length; i++)
    System.out.println(lns[i]);
}

...

 

3. Function WriteLinesToFile(). Write an array of type String[] to a file

When working with files, the function of writing an array of strings of type String[] to a file can be useful. The function uses the capabilities of the FileOutputStream and PrintStream classes.

import java.io.*;

...

// Write an array of type String[] to a file
public static void WriteLinesToFile(String lines[], String filename) throws IOException {

  // 1. Declare internal variables
  FileOutputStream fs = null;
  PrintStream ps = null;

  try {
    // 2. Create instances of classes FileOutputStream, PrintStream
    fs = new FileOutputStream(filename); // create a file stream
    ps = new PrintStream(fs); // associate file stream with PrintStream output stream

    // 3. The loop of writing the lines[] array to the file
    for (int i=0; i<lines.length; i++)
      ps.println(lines[i]);
  }
  catch (IOException e) {
    // If the error opening the file or other error
    System.out.println("I/O error: " + e);
  }
  finally {
    if (fs!=null) {
      try {
        fs.close();
      }
      catch (IOException e2) {
        System.out.println("Error closing " + filename);
      }
    }

    if (ps!=null) {
      ps.close();
    }
  }
}

 

4. Function ReplaceStringInFile(). Replace the specified string in a text file

To replace the specified line in the file, you need to specify its position. Replacing the string is carried out according to the following algorithm:

  • get the lines of the file as an array of String[];
  • replace a string in an array;
  • write the array back to the file.

Using a similar algorithm, you can implement any other file operations. To read lines from a file and write them to a file, you can use the functions from paragraphs 2, 3 of this topic.

The text of the ReplaceStringInFile() function is as follows.

import java.io.*;

...

// Replace a line in a file at a given position
// Function parameters:
// - position - line position in the file;
// - str - a string that replaces a string in a file;
// - filename - name of the file in which the string is replaced.
// If the operation is successful, then the function returns true.
public static boolean ReplaceStringInFile(int position, String str, String filename)
  throws IOException {

  // 1. Perform the necessary checks.
  // Is the position value correct?
  int count = CountLinesInFile(filename); // number lines in the file
  if ((position<0) || (position>=count)) return false;

  // 2. Get a list of file lines
  String lines[] = GetLinesFromFile(filename);

  // 3. Replace string at position
  lines[position] = str;

  // 4. Write modified list of lines back to file
  WriteLinesToFile(lines, filename);

  return true;
}

Using a function can be, for example, the following

...

public static void main(String[] args) throws IOException {
  // Using function ReplaceStringInFile()
  boolean res;
  res = ReplaceStringInFile(7, "0000", "textFile.txt");

  if (res)
    System.out.println("Ok");
  else
    System.out.println("Fail");
}

...

 

5. Function SortLinesInFile(). Sort lines in a file by inserting method

Sorting strings occurs according to the very principle described in paragraph 4. First, the lines of the file are copied to a temporary array of type String[]. Then the temporary array is sorted. In the last step, the sorted array is copied back to the file.

In its work, the SortLinesInFile() function uses the two functions GetLinesFromFile() and WriteLinesToFile(), the implementation of which is described in paragraphs 2, 3.

The text of function is as follows.

import java.io.*;

...

// Sort lines in a file.
// Parameters:
// - filename - the name of the file;
// - order - sorting order,
// if order = true then sort in ascending order.
public static boolean SortLinesInFile(String filename, boolean order)
throws IOException {

  String s;

  // 1. Get the lines of a file as an array of String[]
  String lines[] = GetLinesFromFile(filename);

  // 2. If there are lines in the file, then sort them
  if (lines!=null) {

    // the loop of sorting using the insertion method
    for (int i=0; i<lines.length-1; i++)
      for (int j=i; j>=0; j--)
        if (order) {
          if (lines[j].compareTo(lines[j+1])>0) {
            s = lines[j];
            lines[j] = lines[j+1];
            lines[j+1] = s;
          }
        }
        else {
          if (lines[j].compareTo(lines[j+1])<0) {
            s = lines[j];
            lines[j] = lines[j+1];
            lines[j+1] = s;
          }
        }

    // 3. Write sorted lines to file
    WriteLinesToFile(lines, filename);

    // 4. Return the result
    return true;
  }

  return false;
}

The use of the function may be as follows

public static void main(String[] args) throws IOException {
  // Using the function ReplaceStringInFile()
  boolean res;
  res = SortLinesInFile("textFile.txt", false);

  if (res)
    System.out.println("Ok");
  else
    System.out.println("Fail.");
}

 


Related topics