Thomson Reuters Interview Question
Software Engineer / DevelopersCountry: India
There are multiple issues to be solved here
1.Efficient shift of the file contents so the new changes are added. However ensuring no data is lost.
2.We will need 2 files , Old file where data is read. New file containing the changes and 2 buffers to do the manipulation of replacing the words in the buffer.
Following will be the general algo for this
Divide the file into chunks of say 4kb . Read the chunk ,
Now Identify the occurances of the word in the buffer.
Start from the start of the buffer. On first occurance of the word ,do copy of the original buffer upto the first occurrence into another buffer. Add the new word into this temp buffer. Now again repeat the scan of next occurance.
Continue this process till the destination buffer files up or all the source buffer is scanned. Write the data to new file along with the changes.
package com.test.me;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class ReplaceCode {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// File nfile = new File(System.getProperty("user.dir") +File.separator+"MyTest");
// nfile.mkdir();
File nffile = new File("test.txt");
nffile.createNewFile();
FileWriter flw = new FileWriter(nffile);
BufferedWriter bfl = new BufferedWriter(flw);
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
bfl.write(bfr.readLine());
bfl.flush();
bfl.close();
File nfsdfile = new File("test.txt");
BufferedReader bfrr = new BufferedReader(new FileReader(nfsdfile));
ArrayList<String> nal = new ArrayList<>();
String s = null;
while(null!=(s=bfrr.readLine())){
String[] str = s.split(" ");
Collections.addAll(nal, str);
}
for(int i=0;i<nal.size();i++){
if(nal.get(i).contains("skullcrusher")){
System.out.println("i am here");
// String sla =nal.get(i).replace("skullcrusher", "dracula");
nal.set(i, "dracula");
}
System.out.println(nal.get(i));
}
for(int i=0;i<nal.size();i++){
if(nal.get(i).contains("skullcrusher")){
nal.remove(i);
}
}
File finalFile = new File("testFinal.txt");
nffile.createNewFile();
FileWriter flwl = new FileWriter(finalFile);
BufferedWriter bfll = new BufferedWriter(flwl);
for(String str:nal){
// System.out.println(str);
bfll.write(str);
}
bfll.flush();
bfll.close();
}
}
start backwards, shift all characters by newword - oldword, replace word when found
- bbarodia January 16, 2013