Index154

Sequential ID Replacer

May 14th, 2021 (edited)
408
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. package txtIDReplacer;
  2.  
  3. import java.io.BufferedWriter;
  4. import java.io.File;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.util.Scanner;
  10.  
  11. public class TxtIDReplacer {
  12.  
  13.     // Global variables
  14.     public static String path = "E:\\User\\Downloads\\";
  15.    
  16.     public static void main(String[] args) throws IOException {
  17.        
  18.         // Read the list of replacement values for all IDs
  19.         // Create array
  20.         List<String> names = new ArrayList<String>();
  21.        
  22.         //Start the scanner
  23.         File f = new File(path + "items.txt");
  24.         Scanner s = new Scanner(f);
  25.        
  26.         //Go through the lines and save them into the array
  27.         while(s.hasNext()) {
  28.             String line = s.nextLine();
  29.             names.add(line);
  30.         }
  31.         s.close();
  32.         String[] values = names.toArray(new String[0]);
  33.        
  34.         // Read the main file which contains the IDs
  35.         // Create string
  36.         String mainFile = "";
  37.        
  38.         //Start the scanner
  39.         File f2 = new File(path + "for_replace.txt");
  40.         Scanner s2 = new Scanner(f2);
  41.        
  42.         //Go through the lines and add them to the string
  43.         while(s2.hasNext()) {
  44.             String line = s2.nextLine();
  45.             mainFile = mainFile + "\n" + line;
  46.         }
  47.         s2.close();
  48.        
  49.        
  50.         // Replace all ocurrences of the regex pattern in the main file with the elements of the array
  51.         // It is important to match the IDs in descending order to avoid single-digit IDs replacing everything
  52.         for(int i = values.length - 1; i >= 0; i--) {
  53.             mainFile = mainFile.replaceAll("" + i, values[i]);
  54.         }
  55.        
  56.         // Save to file in output folder
  57.         // Initiate the FileWriter with the designated file path
  58.         FileWriter f3 = new FileWriter(path + "replaced.txt");
  59.         BufferedWriter bW = new BufferedWriter(f3);
  60.         bW.write(mainFile);
  61.         bW.close();
  62.        
  63.         System.out.println("Done!");
  64.        
  65.     }
  66.  
  67. }
Add Comment
Please, Sign In to add comment