Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.FileWriter;
- import java.util.Scanner;
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- /**
- *
- * @author anton
- */
- public class Utils {
- public static String cifradoCesar(String texto, int clave) {
- StringBuilder cifrado = new StringBuilder();
- clave = clave % 26;
- for (int i = 0; i < texto.length(); i++) {
- if (texto.charAt(i) >= 'a' && texto.charAt(i) <= 'z') {
- if ((texto.charAt(i) + clave) > 'z') {
- cifrado.append((char) (texto.charAt(i) + clave - 26));
- } else if ((texto.charAt(i) + clave) < 'a') {
- cifrado.append((char) (texto.charAt(i) + clave + 26));
- } else {
- cifrado.append((char) (texto.charAt(i) + clave));
- }
- } else if (texto.charAt(i) >= 'A' && texto.charAt(i) <= 'Z') {
- if ((texto.charAt(i) + clave) > 'Z') {
- cifrado.append((char) (texto.charAt(i) + clave - 26));
- } else if ((texto.charAt(i) + clave) < 'A') {
- cifrado.append((char) (texto.charAt(i) + clave + 26));
- } else {
- cifrado.append((char) (texto.charAt(i) + clave));
- }
- } else {
- cifrado.append((char) (texto.charAt(i)));
- }
- }
- return cifrado.toString();
- }
- public static void leoYEscribo(File fEntrada, int clave, String nombreFicheroSalida) {
- // fw = null;
- Scanner scFile = null;
- String linea = "";
- try {
- scFile = new Scanner(fEntrada, "UTF-8");
- while (scFile.hasNextLine()) {
- linea = scFile.nextLine();
- escribelo(nombreFicheroSalida, linea, clave);
- }
- } catch (Exception e) {
- System.out.println("Se ha producido un error");
- } finally {
- if (scFile != null) {
- scFile.close();
- }
- }
- }
- public static void escribelo(String nombreFicheroSalida, String linea, int clave) {
- FileWriter fwc = null;
- File fSalida;
- fSalida = new File(nombreFicheroSalida);
- try {
- fwc = new FileWriter(fSalida, true); //True para que continue escribiendo y no sobreescriba
- fwc.write(Utils.cifradoCesar(linea, clave) + "\n");
- } catch (Exception e) {
- System.out.println("Se ha producido un error al escribir" + e.toString());
- } finally {
- if (fwc != null) {
- try {
- fwc.close();
- } catch (Exception e) {
- System.out.println("Se ha producido un error al cerrar el fichero: " + e.toString());
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement