Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*; // for file handling
- import java.util.Scanner; // for user input
- public class ReplaceText {
- /**
- * Program: ReplaceText.java
- * Creator: Chris Clarke
- * Created: 18.10.2012
- * Purpose: Open text file, replace <oldtext> with <newText>, save.
- */
- public static void main(String[] args) {
- String oldText, newText;
- String allText;
- String fileName, backupName;
- String backup;
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter filename, including path: ");
- fileName = scan.nextLine();
- if (fileName.equals("")) {
- System.out.println("No file!");
- return;
- } // end if
- System.out.print("Enter text to be replaced: ");
- oldText = scan.nextLine();
- if (oldText.equals("")) {
- System.out.println("No text entered!");
- return;
- } // end if
- System.out.print("Enter replacement text: ");
- newText = scan.nextLine();
- System.out.println();
- allText = readFromFile(fileName);
- System.out.print("Make backup (y/n)? ");
- backup = scan.nextLine();
- if (backup.toLowerCase().startsWith("y")) {
- System.out.print("Enter backup filename, including path: ");
- backupName = scan.nextLine();
- writeToFile(backupName, allText);
- } // end if
- allText = allText.replaceAll(oldText, newText);
- writeToFile(fileName, allText);
- } // end main
- private static String readFromFile(String fileName) {
- String text = "";
- try {
- // Create the readers.
- FileReader fr = new FileReader(fileName);
- LineNumberReader lnr = new LineNumberReader(fr);
- // Read line by line
- String s = " "; // Anything but null.
- while (s != null) {
- s = lnr.readLine();
- if (s == null) break;
- System.out.println(s); // option to display text
- text += s+"\r\n"; // add line of text plus newline
- } // end while
- // Close the readers.
- lnr.close();
- fr.close();
- }
- catch (IOException x) {
- System.out.println("Trouble reading! " + x.getMessage());
- } // end try...catch
- return text;
- } // end readFromFile
- private static void writeToFile(String fileName, String text) {
- if (text.equals("")) return;
- try {
- // Create the writer.
- BufferedWriter fw = new BufferedWriter(new FileWriter(fileName));
- for (int i=0; i<text.length(); i++) {
- System.out.print(text.charAt(i)); // option to display text
- fw.write(text.charAt(i));
- } // end for
- fw.close();
- System.out.println("File saved.");
- }
- catch (IOException x) {
- System.out.println("Trouble writing! " + x.getMessage());
- } // end try...catch
- } // end writeToFile
- } // end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement