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.");
}

 

6. Writing/reading an array of integers to a text file. Example

The example shows the program code that does the following work:

  • writes an array of integers to the file;
  • reads an array of integers from a file.

To perform the task, the ReadWriteArrayFile class has been developed, in which two methods are implemented:

  • saveToFileTxt() – designed to write an array to a file. The array reference and file name are input parameters to the method;
  • readFromFileTxt() – Reads the array of integers from a file in a predefined format. The file name is passed to the method as an input parameter.

Following this example, you can implement your own methods that perform:

  • writing (saving) data of different types to a file in a given format;
  • reading different types of data from a file in a specific format.

 

import java.util.*;
import java.io.*;

class ReadWriteArrayFile {
  // Write an array of numbers to a text file in the format:
  // - N - amount of numbers;
  // - number1;
  // - number2;
  // - ...
  // - numberN.
  // The parameters of method:
  // - A - array of numbers;
  // - filename - the name of the file.
  void saveToFileTxt(int[] AI, String filename) throws IOException {
    // Link to text file: fOut -> filename
    FileOutputStream fOut = new FileOutputStream(filename);

    // Link to instance fOut: ps -> fOut -> filename
    PrintStream pS = new PrintStream(fOut);

    // Write the array AI
    pS.println(AI.length);       
    for (int i=0; i<AI.length; i++) {
      pS.println(AI[i]);
    }
    pS.close();
    fOut.close();      
  }

  // Read an array of numbers from a text file.
  // File format:
  // - N - amount of numbers;
  // - number1;
  // - number2;
  // - ...
  // - numberN.
  int[] readFromFileTxt(String filename) throws IOException {
    // 1. Associate the file filename with the fInput instance: fInput <- filename
    FileInputStream fInput = new FileInputStream(filename);   

    // 2. Bind an instance of the Scanner class to an instance of fInput:
    //    scanner <- fInput <- filename
    Scanner scanner = new Scanner(fInput);

    // 3. Declare additional variables
    int[] AI = null; // The resulting array
    int count; // The number of integers in an array

    // 4. Read the number of numbers in an array
    count = scanner.nextInt();

    // 5. Allocate memory for array AI
    AI = new int[count];

    // 6. Read numbers
    for (int i=0; i<AI.length; i++)
      AI[i] = scanner.nextInt();

    // 7. Close streams
    scanner.close();
    fInput.close();

    // 8. Return array
    return AI;    
  }   
}

public class Threads {

  public static void main(String[] args) throws IOException {
    // Writing/reading an array of integers to a file
    // 1. Create an instance of the ReadWriteArrayFile class
    ReadWriteArrayFile obj = new ReadWriteArrayFile();

    // 2. Create a testable array
    int[] AI = { 2, 5, -1, 8, 4, 9 };

    // 2. Write the array to file "myFile1.txt"
    obj.saveToFileTxt(AI, "myFile1.txt");

    // 3. Read from file "myFile1.txt"
    int[] AI2 = obj.readFromFileTxt("myFile1.txt");

    // 4. Display array
    System.out.println();
    for (int i=0; i<AI2.length; i++)
      System.out.print(AI2[i] + " ");
    System.out.println();
  }
}

 


Related topics