Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package txtIDReplacer;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Scanner;
- public class TxtIDReplacer {
- // Global variables
- public static String path = "E:\\User\\Downloads\\";
- public static void main(String[] args) throws IOException {
- // Read the list of replacement values for all IDs
- // Create array
- List<String> names = new ArrayList<String>();
- //Start the scanner
- File f = new File(path + "items.txt");
- Scanner s = new Scanner(f);
- //Go through the lines and save them into the array
- while(s.hasNext()) {
- String line = s.nextLine();
- names.add(line);
- }
- s.close();
- String[] values = names.toArray(new String[0]);
- // Read the main file which contains the IDs
- // Create string
- String mainFile = "";
- //Start the scanner
- File f2 = new File(path + "for_replace.txt");
- Scanner s2 = new Scanner(f2);
- //Go through the lines and add them to the string
- while(s2.hasNext()) {
- String line = s2.nextLine();
- mainFile = mainFile + "\n" + line;
- }
- s2.close();
- // Replace all ocurrences of the regex pattern in the main file with the elements of the array
- // It is important to match the IDs in descending order to avoid single-digit IDs replacing everything
- for(int i = values.length - 1; i >= 0; i--) {
- mainFile = mainFile.replaceAll("" + i, values[i]);
- }
- // Save to file in output folder
- // Initiate the FileWriter with the designated file path
- FileWriter f3 = new FileWriter(path + "replaced.txt");
- BufferedWriter bW = new BufferedWriter(f3);
- bW.write(mainFile);
- bW.close();
- System.out.println("Done!");
- }
- }
Add Comment
Please, Sign In to add comment