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

slot gacor

https://badudu.org/

badudu

slot gacor

https://siakad.unikamamuju.ac.id/fonts/-/starlight-princess/

slot88

slot gacor

https://ninjajago.sbs/

https://labskill.umtas.ac.id/wp-content/slot-gacor/

https://kamalinews.co.id/wp-content/slot-deposit-qris/

https://lsgi.org/

https://lsgi.org/

ninjajago

slot777

slot88

http://upforfifty.xyz/

slot gacor

slot gacor

slot88

slot

https://katalog.uinsyahada.ac.id/slot/

situs slot gacor 2023

slot gacor

slot

https://게이코슬롯.com/

gacor88

slot gacor

slot thailand

slot demo

slot gacor

slot gacor

https://siakad.poltekbangmedan.ac.id/images/

slot gacor

slot gacor 4d

slot gacor

situs slot gacor

slot gacor

situs slot gacor

https://setda.blorakab.go.id/packages/upload/galeri/

slot demo

rtp slot

slot gacor

slot88

slot gacor

https://plti.amikompurwokerto.ac.id/wp-content/pages/?tunnel=Slot%20Tongkat%20123

slot88

slot-gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot gacor

slot demo

slot88/

https://smartvillage.tubankab.go.id/vendor/

https://manajemen.unik-kediri.ac.id/wp-content/files/-/slot-toto/

https://myexist.muallimaat.sch.id/.well-known/

slot gacor

toto macau

slot gacor

slot gacor

slot gacor hari ini

slot-gacor

slot gacor

http://student.unisbank.ac.id/wp-includes/slot-gacor-hari-ini/

https://keclasem.rembangkab.go.id/error/

https://ak.polnep.ac.id/slot-gacor/

slot thailand

https://pmbtest.akpergshwng.ac.id/data/slot-qris-gacor/

slot gacor 4d

https://elsa.polteksahid.ac.id/elsa/files/slot-gacor-thailand/

https://ppdb.smai-soedirman-kotabekasi.sch.id/assets/

slot-gacor

slot-gacor

olxtoto

slot gacor

slot88

slot gacor

slot gacor

https://roadpowersystems.com/pages/

https://disdikbud.pemkomedan.go.id/assets/css/

slot4d

slot gacor

slot gacor

slot gacor

slot thailand

togel online

slot88

https://diafrica.org/pages/

togel online

slot gacor

https://fkomputer.umku.ac.id/wp-content/plugins/

slot gacor

slot gacor

slot gacor

https://feb.umku.ac.id/wp-includes/

https://fgizi.umku.ac.id/wp-content/languages/

https://fmipa.umku.ac.id/wp-includes/

slot gacor

slot88

slot88

slot gacor

slot gacor

slot gacor

slot gacor

https://fkip.umku.ac.id/wp-content/uploads/

https://fkesehatan.umku.ac.id/wp-content/plugins/

slot gacor

https://fst.umku.ac.id/wp-content/plugins/

https://fkeperawatan.umku.ac.id/wp-content/plugins/

olx toto

https://akparjakarta.ac.id/wp-content/

slot qris

slot qris

slot gacor

slot gacor

slot gopay

slot gacor

https://siakad.poltekbangmedan.ac.id/images/

slot thailand

slot gacor

slot gopay

https://ppdb.smai-soedirman-kotabekasi.sch.id/assets/

https://pmbtest.akpergshwng.ac.id/data/slot-qris-gacor/

https://cbt.dindikbud.pekalongankab.go.id/assets/

slot ovo

https://jdih.pn-labuanbajo.go.id/images/

https://pn-labuanbajo.go.id/wp-content/uploads/

https://fst.umku.ac.id/wp-content/uploads/

slot gacor

slot88

slot gacor

slot gacor

slot gacor

slot88

slot gacor

https://smkpelitanusantara.sch.id/

https://wibs.sch.id/

https://mnis.sch.id/

https://smkm3-alkamal.sch.id/

https://pelitanusantara.sch.id/

slot hoki

slot gacor kamboja

slot777

slot gacor 4d

http://esptpd.kaimanakab.go.id/public/img/

slot gacor

slot gacor

slot server luar

slot gacor

slot demo

slot88

slot hoki

https://api.kelastryout.id/assets/

https://siasuh.poltekbangmedan.ac.id/pedoman/ninjajago/

slot gacor

slot gacor

slot