Created
March 11, 2016 09:19
-
-
Save aliharis/171ae1d2e5e692a0e351 to your computer and use it in GitHub Desktop.
Function for replacing the nth occurrence of a character in nth line. Results: http://oi63.tinypic.com/2wm17ig.jpg
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package javaapplication1; | |
import java.io.BufferedReader; | |
import java.io.BufferedWriter; | |
import java.io.FileNotFoundException; | |
import java.io.FileReader; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
/** | |
* | |
* @author haris | |
*/ | |
public class CharacterReplace { | |
public static void main(String args[]) { | |
String file = "/Users/haris/Desktop/src.txt"; | |
try { | |
CharacterReplace.textReplace(file, "_", "X", 1, 3); | |
CharacterReplace.textReplace(file, "_", "Y", 2, 2); | |
CharacterReplace.textReplace(file, "_", "A", 4, 5); | |
CharacterReplace.textReplace(file, "_", "B", 5, 4); | |
} catch (Exception e) { | |
System.out.println("Exception Caught. Printing Stacktrace:"); | |
e.printStackTrace(); | |
} | |
} | |
public static void textReplace(String file, String subject, String replacement, int line, int index) | |
throws FileNotFoundException, IOException { | |
final StringBuilder contents; | |
// Read the contents of the file | |
try (BufferedReader reader = new BufferedReader(new FileReader(file))) { | |
contents = new StringBuilder(); | |
int currentLine = 1; | |
// Read the file contents line by line | |
while (reader.ready()) { | |
StringBuffer tmp = new StringBuffer(); | |
// Check if the current line is the line to be replaced | |
if (currentLine == line) { | |
int currentIndex = 0; | |
Pattern pattern = Pattern.compile(subject); | |
Matcher matcher = pattern.matcher(reader.readLine()); | |
// Find the index and replace | |
while (matcher.find()) | |
if (++currentIndex == index) | |
matcher.appendReplacement(tmp, replacement); | |
matcher.appendTail(tmp); | |
} else { | |
tmp.append(reader.readLine()); | |
} | |
// Append to a string | |
contents.append(tmp.toString()).append("\n"); | |
currentLine++; | |
} | |
} | |
// Overwrite the file with processed data | |
final String stringContents = contents.toString(); | |
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) { | |
writer.write(stringContents); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment