Skip to content

Instantly share code, notes, and snippets.

@borncorp
Created July 2, 2014 07:10
Show Gist options
  • Save borncorp/2016ce4f89d3da0f4801 to your computer and use it in GitHub Desktop.
Save borncorp/2016ce4f89d3da0f4801 to your computer and use it in GitHub Desktop.
Writes to a file, reads from a file, and searches and replaces words in the file and rewrites to the file.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class Main {
static PrintWriter writer;
static List<String> lines;
public static void main(String[] args) throws IOException {
createFile();
writetofile("Apple");
writetofile("Microsoft");
writetofile("Facebook");
readFile();
System.out.println(lines);
writetofile("Yahoo!!");
readFile();
System.out.println(lines);
searchAndReplace("Yahoo", "Google");
readFile();
System.out.println(lines);
closefile();
}
public static void writetofile () {
writer.flush();
}
public static void writetofile (String texttoadd) {
writer.println(texttoadd);
writer.flush();
}
public static void createFile () throws FileNotFoundException, UnsupportedEncodingException {
writer = new PrintWriter("E:\\=== USUARIO BORN ===\\Desktop\\the-file-name.txt", "UTF-8");
}
private static void readFile() throws IOException {
Path path = FileSystems.getDefault().getPath("E:\\=== USUARIO BORN ===\\Desktop\\the-file-name.txt");
lines = Files.readAllLines(path, StandardCharsets.UTF_8);
}
private static void closefile() {
writer.close();
}
private static void searchAndReplace(String toSearch, String toReplace) throws IOException {
readFile();
createFile();
for (int i = 0; i < lines.size(); i++) {
String aString=lines.get(i);
writetofile(aString.replaceAll(toSearch, toReplace));
writer.flush();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment