0% encontró este documento útil (0 votos)
411 vistas19 páginas

Ejercicios de Ficheros en Java

El documento presenta varios ejercicios sobre el manejo de ficheros en Java. En el primer punto, se describen ejercicios para leer un fichero de texto carácter a carácter, escribir y mostrar el contenido de un fichero introduciendo la ruta y texto por teclado, e indicar si un fichero existe basado en la ruta de entrada. El segundo punto propone un menú para crear un fichero con datos personales, mostrar el contenido del fichero creado, y salir del programa.
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
411 vistas19 páginas

Ejercicios de Ficheros en Java

El documento presenta varios ejercicios sobre el manejo de ficheros en Java. En el primer punto, se describen ejercicios para leer un fichero de texto carácter a carácter, escribir y mostrar el contenido de un fichero introduciendo la ruta y texto por teclado, e indicar si un fichero existe basado en la ruta de entrada. El segundo punto propone un menú para crear un fichero con datos personales, mostrar el contenido del fichero creado, y salir del programa.
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd

EJERCICIOS EN JAVA

1. EJERCICIOS DE FICHEROS

a. 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 Mundo”, deberá mostrar
“HolaMundo”.

Programa 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);
}
}
}

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

c. 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.
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;
}
}

d. 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.
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
}

e. 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.
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();
}
}
}
2. OTRAS OPCIONES DE FICHEROS

Realiza un programa en JAVA en el quemuestres un menu que te permita 3


opciones:
1. Creacion de un fichero de texto (con el nombre que tu quieras) en el que indiques en
cada linea:
Tu Nombre.
Tus Apellidos.
Tu Ciudad de Nacimiento.
2. Mostrar por pantalla el contenido del fichero de texto creado.
3. Salir del Programa.

public class Ejercicio01 {

public static void mostrarMenu() {

Scanner teclado = new Scanner(System.in);

int opcion;

do {

System.out.println("1-.Crear Fichero");

System.out.println("2-.Mostrar Fichero");

System.out.println("3-.Salir");

opcion = teclado.nextInt();

switch (opcion) {

case 1: {

crearFichero();

break;

case 2: {

mostrarFichero();

break;

case 3: {

System.out.println("Gracias por usar el programa");


}

default: {

System.out.println("Opcion incorrecta");

} while (opcion != 3);

public static void crearFichero() {

FileWriter fw = null;

try {

fw = new FileWriter("archivo.txt");

PrintWriter pw = new PrintWriter(fw);

escribirFichero(pw);

} catch (Exception e) {

System.out.println(e.getMessage());

} finally {

try {

if (fw != null) {

fw.close();

} catch (Exception e) {

System.out.println(e.getMessage());

public static void escribirFichero(PrintWriter pw) throws Exception {

Scanner teclado = new Scanner(System.in);

String opcion;

System.out.println("Introduce tu nombre");

opcion = teclado.nextLine();

pw.println(opcion);

System.out.println("Introduce tus apellidos");

opcion = teclado.nextLine();
pw.println(opcion);

System.out.println("Introduce tu lugar de nacimiento");

opcion = teclado.nextLine();

pw.println(opcion);

public static void leerFichero(BufferedReader br) throws Exception {

String linea;

linea = br.readLine();

while (linea != null) {

System.out.println(linea);

linea = br.readLine();

public static void mostrarFichero() {

FileReader fr = null;

try {

File fichero = new File("archivo.txt");

fr = new FileReader(fichero);

BufferedReader br = new BufferedReader(fr);

leerFichero(br);

} catch (Exception e) {

System.out.println(e.getMessage());

} finally {

try {

if (fr != null) {

fr.close();

} catch (Exception e) {

System.out.println(e.getMessage());

public static void main(String[] args) {

mostrarMenu();

}
 

b. Realiza un programa en JAVA en el quemuestres un menú que te permita 3


opciones:
1. Volcado de un array con los 100 primeros números pares a un fichero de texto. El
nombre del fichero lo elegirá el usuario.
2. Mostrar por pantalla el contenido del fichero de texto creado.
3. Salir del Programa.

package ejercicio02tema08;

import java.io.*;

import java.util.Scanner;

public class Ejercicio02Tema08 {

static String nombre;

public static void mostrarMenu() {

Scanner teclado = new Scanner(System.in);

int opcion;

do {

System.out.println("1.- Crear fichero");

System.out.println("2.- Mostrar Fichero");

System.out.println("3.- Salir");

opcion = teclado.nextInt();

switch (opcion){

case 1 : {

crearFichero();

break;

case 2 : {

mostrarFichero();

break;

case 3 : {

System.out.println("Gracias por usar el Programa");

break;

default:{
System.out.println("Opcion no Valida");

} while (opcion != 3);

public static String elegirNombre() {

Scanner teclado = new Scanner(System.in);

System.out.println("Introduce el nombre del Archivo");

nombre = teclado.nextLine();

return nombre;

public static String devolverNombre() {

return nombre;

public static void crearFichero() {

FileWriter fw = null;

try {

fw = new FileWriter(elegirNombre() + ".txt");

PrintWriter pw = new PrintWriter(fw);

escribirFicheo(pw);

} catch (Exception e) {

System.out.println(e.getMessage());

}finally{

try {

if (fw != null) {

fw.close();

} catch (Exception e) {

System.out.println(e.getMessage());

public static void escribirFicheo(PrintWriter pw) throws Exception{


for (int i = 0; i < 100; i++) {

if (i % 2 == 0 ) {

pw.println(i);

public static void mostrarFichero() {

FileReader fr = null;

try {

File fichero = new File(devolverNombre()+ ".txt");

fr = new FileReader(fichero);

BufferedReader br = new BufferedReader(fr);

leerFichero(br);

} catch (Exception e) {

System.out.println(e.getMessage());

}finally{

if (fr != null) {

try {

fr.close();

} catch (Exception e) {

System.out.println(e.getMessage());

public static void leerFichero(BufferedReader br)throws Exception{

String linea;

linea = br.readLine();

while (linea != null) {

System.out.println(linea);

linea = br.readLine();

}
}

public static void main(String[] args) {

mostrarMenu();

c. Crea un fichero de texto, en el Bloc de Notas, con el nombre y contenido que tú quieras. Ahora
crea una aplicación en JAVA que lea este fichero de texto (¡OJO!  Carácter a carácter, no línea a
línea) y muestre su contenido por pantalla sin espacios.
• Por ejemplo, si un fichero contiene el texto “Esto es una prueba”, deberá mostrar por
pantalla “Estoesunaprueba”.

public class Ejercicio03tema08 {

public static void mostrarFichero() {

FileReader fr = null;

try {

File fichero = new File("pp.txt");

fr = new FileReader(fichero);

leerFichero(fr);

} catch (Exception e) {

System.out.println(e.getMessage());

}finally{

if (fr != null) {
try {

fr.close();

} catch (Exception e) {

System.out.println(e.getMessage());

public static void leerFichero(FileReader fr) throws Exception{

int letra;

char caracter;

letra = fr.read();

while (letra != -1) {

caracter=(char)letra;

System.out.print(caracter);
letra = fr.read();

public static void main(String[] args) {

mostrarFichero();

d. Crea una aplicación donde pidamos el nombre de un fichero por teclado y un texto que queramos
escribir en el fichero.
Después de crear el fichero con la información introducida, deberás mostrar por pantalla e texto
del fichero pero variando entre mayúsculas y minúsculas.
• Por ejemplo, si escribo:
“Bienvenidos a Plasencia” deberá devolver
“bIENVENIDOS A AREQUIPA”.

public class Ejercicio04Tema08 {

static String nombreFichero;

static String testo;

public static String solicitarFichero() {

Scanner teclado = new Scanner(System.in);

System.out.println("Introduce el nombre del fichero");

nombreFichero = teclado.nextLine();

return nombreFichero;

public static String devolverFichero() {

return nombreFichero;

public static String solicitarTesto() {

Scanner teclado = new Scanner(System.in);

System.out.println("Introduce el Testo del fichero");

testo = teclado.nextLine();

return testo;

public static String devolverTesto() {


return testo;

public static void crearFichero() {

FileWriter fw = null;

try {

fw = new FileWriter(solicitarFichero() + ".txt");

PrintWriter pw = new PrintWriter(fw);

escribirFichero(pw);

} catch (Exception e) {

System.out.println(e.getMessage());

}finally{

try {

if (fw != null) {

fw.close();

} catch (Exception e) {

System.out.println(e.getMessage());

public static void escribirFichero(PrintWriter pw) throws Exception{

pw.println(solicitarTesto());

public static void mostrarFichero() {

FileReader fr = null;

try {

File fichero = new File(devolverFichero() + ".txt");

fr = new FileReader(fichero);

BufferedReader br = new BufferedReader(fr);

leerFichero(br);

} catch (Exception e) {

System.out.println(e.getMessage());

} finally {
try {

if (fr != null) {

fr.close();

} catch (Exception e) {

System.out.println(e.getMessage());

public static void leerFichero(BufferedReader br)throws Exception{

public static void invertirCadena(String cadena, char [] cadenaMinusculas,

char [] cadenaMaysculas){

char [] cadenaFinal;

cadenaFinal= cadena.toCharArray();

char [] cadenaChar;

cadenaChar = cadena.toCharArray();

for (int i = 0; i < cadenaChar.length; i++) {

for (int j = 0; j < cadenaMinusculas.length; j++) {

if (cadenaChar[i] == cadenaMinusculas[j]) {

cadenaFinal[i] = cadenaMaysculas[j];

if (cadenaChar[i] == cadenaMaysculas[j]) {

cadenaFinal[i] = cadenaMinusculas[j];

}
 

System.out.println(cadenaFinal);

public static void main(String[] args) {

crearFichero();

String cadena = new String(devolverTesto());

char[] cadenaMinusculas = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',

'j', 'q', 'l', 'm', 'n', 'ñ', 'o', 'p', 'k', 'r', 's', 't', 'u', 'v', 'w', 'x',

'y', 'z'};

char[] cadenaMaysculas = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',

'J', 'Q', 'L', 'M', 'N', 'Ñ', 'O', 'P', 'K', 'R', 'S', 'T', 'U', 'V', 'W', 'X',

'Y', 'Z'};

invertirCadena(cadena, cadenaMinusculas, cadenaMaysculas);

f. Realiza un programa en JAVA que lea un archivo creado en el bloc de notas llamado numeros.txt
que contiene varias líneas y en cada una de ellas un número. Luego, el programa te dará la suma de
todos los números del fichero.

g. public class Ejercicio09Tema08 {

h.  

i. public static void mostrarFichero() {

j. FileReader fr = null;

k. try {

l. File fichero = new File("numeros.txt");

m. fr = new FileReader(fichero);

n. BufferedReader br = new BufferedReader(fr);

o. leerFichero(br);
p. } catch (Exception e) {

q. System.out.println(e.getMessage());

r. } finally {

s. try {

t. if (fr != null) {

u. fr.close();

v. }

w. } catch (Exception e) {

x. System.out.println(e.getMessage());

y. }

z. }

aa. }

bb.  

cc. public static void leerFichero(BufferedReader br) throws Exception {

dd. String linea;

ee. int suma = 0;

ff. int num;

gg.  

hh. linea = br.readLine();

ii.  

jj. while (linea != null) {

kk.  

ll. num = Integer.parseInt(linea);

mm. suma = suma + num;

nn. linea = br.readLine();

oo. }

pp. System.out.println("La suma de los numeros es: " + suma);

qq. }
rr.  

ss. public static void main(String[] args) {

tt. mostrarFichero();

uu. }

vv.  

ww. }

xx.
3.

También podría gustarte