I need help with a util
java.
In the program I'm making I need a find and replace
.
I need it to work with text and excel documents.
I can't use the tools of programs like notepad
or the same excel
to make the find and replace
. Since they ask me to be automatic, it is for a web application uploading to the database and some of the data files arrive with data that needs to be replaced.
At the moment I have this
static void modifyFile(String filePath, String oldString, String newString){
File fileToBeModified = new File(filePath);
String oldContent = "";
BufferedReader reader = null;
FileWriter writer = null;
try
{
reader = new BufferedReader(new FileReader(fileToBeModified));
//Lectura de todas las líneas del archivo
String line = reader.readLine();
while (line != null)
{
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
//Reemplazo el contenido viejo
String newContent = oldContent.replaceAll(oldString, newString);
//Reescrivo el fichero
writer = new FileWriter(fileToBeModified);
writer.write(newContent);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args){
modifyFile("file.txt", ".", "0");
System.out.println("done");
}
It replaces the file, but not the points, if not all integer by 0.
The problem is that you use
replaceAll
.The first parameter is a string representing a regex and period means any character.
You have to escape the dot character
\\.
as long asmodifyFile("file.txt", "\\.", "0");