Advertisement
Marin126

UTILS IA Entregable

Apr 2nd, 2020
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.98 KB | None | 0 0
  1.  
  2. import java.io.File;
  3. import java.io.FileWriter;
  4. import java.util.Scanner;
  5.  
  6. /*
  7. * To change this license header, choose License Headers in Project Properties.
  8. * To change this template file, choose Tools | Templates
  9. * and open the template in the editor.
  10. */
  11. /**
  12. *
  13. * @author anton
  14. */
  15. public class Utils {
  16.  
  17. public static String cifradoCesar(String texto, int clave) {
  18. StringBuilder cifrado = new StringBuilder();
  19. clave = clave % 26;
  20. for (int i = 0; i < texto.length(); i++) {
  21. if (texto.charAt(i) >= 'a' && texto.charAt(i) <= 'z') {
  22. if ((texto.charAt(i) + clave) > 'z') {
  23. cifrado.append((char) (texto.charAt(i) + clave - 26));
  24.  
  25. } else if ((texto.charAt(i) + clave) < 'a') {
  26. cifrado.append((char) (texto.charAt(i) + clave + 26));
  27. } else {
  28. cifrado.append((char) (texto.charAt(i) + clave));
  29. }
  30. } else if (texto.charAt(i) >= 'A' && texto.charAt(i) <= 'Z') {
  31. if ((texto.charAt(i) + clave) > 'Z') {
  32. cifrado.append((char) (texto.charAt(i) + clave - 26));
  33. } else if ((texto.charAt(i) + clave) < 'A') {
  34. cifrado.append((char) (texto.charAt(i) + clave + 26));
  35. } else {
  36. cifrado.append((char) (texto.charAt(i) + clave));
  37. }
  38. } else {
  39. cifrado.append((char) (texto.charAt(i)));
  40. }
  41. }
  42. return cifrado.toString();
  43. }
  44. public static void leoYEscribo(File fEntrada, int clave, String nombreFicheroSalida) {
  45. // fw = null;
  46. Scanner scFile = null;
  47. String linea = "";
  48. try {
  49. scFile = new Scanner(fEntrada, "UTF-8");
  50. while (scFile.hasNextLine()) {
  51. linea = scFile.nextLine();
  52. escribelo(nombreFicheroSalida, linea, clave);
  53. }
  54.  
  55. } catch (Exception e) {
  56. System.out.println("Se ha producido un error");
  57. } finally {
  58. if (scFile != null) {
  59. scFile.close();
  60. }
  61. }
  62. }
  63.  
  64. public static void escribelo(String nombreFicheroSalida, String linea, int clave) {
  65. FileWriter fwc = null;
  66. File fSalida;
  67. fSalida = new File(nombreFicheroSalida);
  68.  
  69. try {
  70. fwc = new FileWriter(fSalida, true); //True para que continue escribiendo y no sobreescriba
  71. fwc.write(Utils.cifradoCesar(linea, clave) + "\n");
  72. } catch (Exception e) {
  73. System.out.println("Se ha producido un error al escribir" + e.toString());
  74. } finally {
  75. if (fwc != null) {
  76. try {
  77. fwc.close();
  78. } catch (Exception e) {
  79. System.out.println("Se ha producido un error al cerrar el fichero: " + e.toString());
  80. }
  81. }
  82. }
  83.  
  84. }
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement