Ejercicios resueltos Ficheros en Java

Ejercicio 1

Crea un fichero de texto con el nombre y contenido que tú desees. Por ejemplo, Ejercicio1.txt

Realiza un programa en Java que lea el fichero <<Ejercicio1.txt>> carácter a carácter y muestre su contenido por pantalla  sin espacios.

Por ejemplo, si el fichero contiene el siguiente texto “Hola que haces”, deberá mostrar “Holaquehaces”.

Captura las excepciones que consideres necesarias.

import java.io.FileReader;
import java.io.IOException;

public class Ejercicio1 {

	public static void main(String[] args) {

		final String nomFichero = "D:\\Ejercicio1.txt";
		try (FileReader fich = new FileReader(nomFichero)) {

			int valor = fich.read();
			while (valor != -1) {
				// El carácter ASCII 32 es el espacio. Si el carácter es un espacio no lo
				// escribe.
				if (valor != 32) {
					System.out.print((char) valor);
				}
				valor = fich.read();
			}
		} catch (IOException e) {
			System.out.println("Fichero no existe o ruta fichero incorrecta " + e);
		}
	}
}

Ejercicio 2

Realiza un programa en Java donde introduzcas la ruta de un fichero por teclado y un texto que queramos a escribir en el fichero con JOptionPane.showInputDialog

Posteriormente, muestra el contenido del fichero.

import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JOptionPane;

public class Ejercicio2 {

	public static void main(String[] args) {

		String ruta = JOptionPane.showInputDialog("Introduce la ruta del fichero");
		String texto = JOptionPane.showInputDialog("Introduce el texto que quieres escribir en el fichero");
		escribirFichero(ruta, texto);

		mostrarFichero(ruta);

	}

	public static void escribirFichero(String nomFich, String texto) {
		try (FileWriter fich = new FileWriter(nomFich);) {

			// Escribimos el texto en el fichero
			fich.write(texto);

		} catch (IOException e) {
			System.out.println("Error al escribir en el fichero " + e);
		}
	}

	public static void mostrarFichero(String nomFich) {

		System.out.println("El contenido de: " + nomFich + " es: ");
		// Leemos texto del fichero
		try (FileReader fr = new FileReader(nomFich)) {

			int caracter = fr.read();

			while (caracter != -1) {

				System.out.print((char) caracter);
				caracter = fr.read();
			}

		} catch (IOException e) {
			System.out.println("Problema con la lectura/excritura en el fichero " + e);
		}

	}

}

Ejercicio 3

Realiza un programa en Java donde introduzcas la ruta de un fichero a través del paso de parámetros de Eclipse y te indique si el fichero existe o de lo contrario no existe.

Si faltan argumentos en el main() se debe mostrar un mensaje indicándolo.

Posteriormente mostrar el número de caracteres del fichero.

Para pasar argumentos al main() en eclipse, Run Configurations>Seleccionamos archivo>Arguments

Java Run Configurations Eclipse

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Ejercicio3 {
	FileReader fich;
	
	
	public static void main(String[] args) throws IOException {
		
			if (args.length == 0) {
				System.out.println("Faltan argumentos en main...");
				return;
			}

			for (int i = 0; i < args.length; i++) {
				File fichero = new File(args[i]); // declarar fichero
				if (fichero.exists()) {
					FileReader fich = new FileReader(fichero); // crear el flujo de entrada
					System.out.println("El fichero existe.");
					System.out.println("El fichero tiene: "+contar(fich)+ " caracteres.");
				} else
					System.out.printf("El fichero [%s] no existe...%n", args[i]);
			}

		}//Fin main
		
		
			private static int contar(FileReader fich) throws IOException {
				
				int c = 0;
				while ((fich.read()) != -1) // se va leyendo un carácter
					c++;
				return c;
				
			}

	}

 

Ejercicio 4

Realiza un programa en Java donde introduzcas la ruta de un fichero a través del paso de parámetros de Eclipse y te indique si el fichero existe o de lo contrario no existe.

Si faltan argumentos en el main() se debe mostrar un mensaje indicándolo.

Posteriormente mostrar el número de palabras del fichero.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class Ejercicio4 {
	FileReader fich;

	public static void main(String[] args) throws IOException {

		if (args.length == 0) {
			System.out.println("Faltan argumentos en main...");
			return;
		}

		for (int i = 0; i < args.length; i++) {
			File fichero = new File(args[i]); // declarar fichero
			if (fichero.exists()) {
				FileReader fich = new FileReader(fichero); // crear el flujo de entrada
				System.out.println("El fichero existe.");
				System.out.println("El fichero tiene: " + ContarPalabras(fich) + " palabras.");
			} else
				System.out.printf("El fichero [%s] no existe...%n", args[i]);
		}

	}// Fin main

	static int ContarPalabras(FileReader fich) throws IOException {
		int palabras = 0;
		BufferedReader lee = new BufferedReader(fich);
		String linea;

		while ((linea = lee.readLine()) != null) {
			StringTokenizer st = new StringTokenizer(linea);
			while (st.hasMoreTokens()) {
				String palabra = st.nextToken();
				palabras++;
			}
		} // while

		lee.close();
		return palabras;
	}// ContarPalabras

}

Ejercicio 5

Realiza un programa en Java donde introduzcas la ruta de un fichero a través del paso de parámetros de Eclipse y te indique si el fichero existe o de lo contrario no existe.

Si faltan argumentos en el main() se debe mostrar un mensaje indicándolo.

Posteriormente si por el paso de parámetros pasamos un fichero cuyo contenido son caracteres en mayúscula los debe transformar en caracteres en minúscula y viceversa.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Ut2 {
    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("No hay argumentos");
            return;
        }

        File file = new File(args[0]);
        if (file.exists()) {
            System.out.println("El fichero existe");
        } else {
            System.out.println("El fichero no existe");
            return;
        }

        new ThreadMostrarFichero(file).start();
    }
}


class ThreadMostrarFichero extends Thread {

    File file;

    public ThreadMostrarFichero(File file) {
        super();
        this.file = file;
    }

    @Override
    public void run() {
        System.out.println("Contenido del fichero cambiando las mayusculas por minusculas y viceversa:");
        leerFicheroCambiarMayuscula();
    }

    private void leerFicheroCambiarMayuscula() {
        char caracter;
        try (FileReader fileReader = new FileReader(file)) {
            do {
                caracter = (char) fileReader.read();
                if(caracter == 65535){
                    return;
                }
                if(caracter == ' '){
                    System.out.print(caracter);
                    continue;
                }
                if(caracter < 'a'){
                    System.out.print((char)(caracter + ('a' - 'A')));
                }else{
                    System.out.print((char)(caracter - ('a' - 'A')));
                }
            } while (true);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

 

Deja un comentario

slot gacor

slot88

slot gacor

slot88

https://fatamorgana.co.id/

slot gacor

slot777

https://descubripunilla.com

slot gacor

slot gacor

slot gacor

slot gacor

https://badudu.org/

badudu

slot gacor

https://season8.org

https://oooms.org/

https://jumpyplace.org/

situs slot gacor

slot gacor

info slot gacor

https://diafrica.org/

https://diafrica.org/

http://diafrica.org/

https://advy.ac.id/

slot

slot gacor

slot online

https://instiper.ac.id/

slot gacor

slot online

slot

situs slot gacor

https://kyani.ac.id/

slot gacor

https://pelitanusa.ac.id

slot gacor

https://lsgi.org/

https://lsgi.org/

https://lullabies-of-europe.org/

https://saint-lazarus.org/

https://gregkeyes.com/

slot

slot88

slot gacor

slot hoki

slot gacor

slot gacor

slot88

slot

slot gacor

slot-gacor

slot gacor

slot gacor

slot gacor

rtp live

slot online

info slot gacor

slot gacor

slot777

slot777

slot777

slot88

slot gacor

slot88

slot gacor

slot88

slot gacor

slot gacor

slot

slot maxwin

slot88

slot

slot gacor

slot gacor

slot

slot online

slot

slot gacor

slot777

slot gacor

slot gacor

slot88

slot gacor

slot88

slot gacor

slot online

slot gacor

slot

slot online

slot online

slot

slot gacor

slot gacor

slot88

http://bkddiklat.boalemokab.go.id/slot-gacor/

http://book.iaincurup.ac.id/slot-gacor/

slot gacor

slot online

slot777

slot

https://sipsakato.sumbarprov.go.id/slot-gacor/

slot gacor

https://instiper.ac.id/slot88/

slot88

slot-gacor

slot online

slot gacor hari ini

slot gacor

slot gacor hari ini

slot gacor

slot online

slot

situs slot gacor

slot88

slot online

slot gacor

slot online

slot gacor

slot

slot

slot gacor

slot gacor terbaru

slot gacor

slot pulsa

slot gacor

slot gacor

slot88

slot88

slot gacor

slot gacor terpercaya

slot gacor hari ini

slot88

slot gacor

slot gacor

slot88

slot88

slot gacor

slot online

slot gacor

slot88

slot gacor

slot gacor

slot gacor

slot gacor

situs slot gacor

https://ukm-futsal.upr.ac.id/assets/slot-gacor/

https://ukm-futsal.upr.ac.id/slot-dana/

https://ukm-futsal.upr.ac.id/assets/slot-gacor-hari-ini/

slot gacor

slot online

slot gacor

slot gacor

slot88

slot gacor

https://bkd.bantenprov.go.id/bkdlama/

slot pulsa

slot gacor

slot online

rtp slot gacor

slot deposit dana

slot gacor

https://human.udru.ac.th/site/togel-100perak/

slot maxwin

slot gacor

slot777

slot gacor

slot gacor

slot gacor

slot88

slot dana

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot88

slot88

slot gacor

slot88

slot gacor

slot88

slot gacor

slot gacor

slot88

slot gacor

slot88

slot gacor

slot gacor

slot gacor maxwin

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot88