Java File Handling: Reading Text and Managing Files

Classified in Computers

Written on in English with a size of 4.37 KB

Java File Handling Examples: Reading Text and Managing Files

This document presents two distinct Java examples demonstrating fundamental Input/Output (I/O) operations, including reading data from text files and managing file existence and metadata.

Example 1: Reading and Summing Numbers from a Text File

This program reads characters from a file named pepe.txt using FileReader. It attempts to parse and sum numerical values found within the file. Note the specific logic used for character processing and summation.

Java Code: Summing File Contents (EjerciciosFiletexto2)

package ejerciciosfiletexto2;
import java.io.FileReader;
import java.io.IOException;

/**
 *
 * @author thene
 */
public class EjerciciosFiletexto2 {    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args){
        int suma = 0;
        try {
            
            FileReader fr = new FileReader("pepe.txt"); 
            
            int i = 0;
            String number = "";
            
            while ((i = fr.read()) != -1) {
                if (i != 10) { // 10 is the ASCII value for newline (\n)
                    number += (char)i;
                    // Note: This implementation sums intermediate substrings.
                    suma += Integer.parseInt(number);
                } else {
                    number = "";
                }
            }
            fr.close();
            System.out.println("Resultado =" + suma);
        } catch (Exception ex) {
            System.out.println("Error con el archivo");
            ex.printStackTrace();
        }
    }
}

Key Implementation Details

  • The program uses FileReader for character stream input.
  • It handles potential IOException using a try-catch block.
  • The character code 10 is used to detect line breaks, resetting the current number string.

Example 2: File Existence Check and Creation Utility

This utility prompts the user for a file path or name. It then checks if the specified file exists. If it exists, it displays key metadata (name, canonical path, length). If it does not exist, the program attempts to create a new file at the specified location.

Java Code: File Management Utility (EjercicioFile3)

package ejerciciofile3;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author thene
 */
public class EjercicioFile3 {    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        File ubicacion;
        Scanner teclado = new Scanner(System.in);
        
        System.out.println("Introduce la ruta del archivo o el nombre que quieras crear o sacar informacion ");
        String rutaoNombre = teclado.nextLine();
        ubicacion = new File(rutaoNombre);
        
        if (ubicacion.exists()){
            try {
                System.out.println("Informacion: ");               
                System.out.println(ubicacion.getName());                
                System.out.println(ubicacion.getCanonicalPath());                
                System.out.println(ubicacion.length());
            } catch (IOException ex) {               
                Logger.getLogger(EjercicioFile3.class.getName()).log(Level.SEVERE, null, ex);
            }
       } else {
            try {
                ubicacion.createNewFile();
            } catch (IOException ex) {                   
                Logger.getLogger(EjercicioFile3.class.getName()).log(Level.SEVERE, null, ex);
            }
        }       
    }    
}

User Input and File Metadata Retrieval

The program utilizes the Scanner class to capture user input for the file path. The File class methods used for metadata retrieval include:

  • getName(): Retrieves the file name.
  • getCanonicalPath(): Retrieves the absolute, normalized path.
  • length(): Retrieves the size of the file in bytes.
  • createNewFile(): Attempts to atomically create a new, empty file.

Logging is implemented using java.util.logging.Logger to handle exceptions during file operations.

Related entries: