Search code examples
javafile-manipulation

File manipulation (changing lines in a File) in java


I'm trying to read in a file and change some lines.

The instruction reads "invoking java Exercise12_11 John filename removes the string John from the specified file."

Here is the code I've written so far

import java.util.Scanner;
import java.io.*;
public class Exercise12_11 {

public static void main(String[] args) throws Exception{

    System.out.println("Enter a String and the file name.");

    if(args.length != 2) {
        System.out.println("Input invalid. Example: John filename");
        System.exit(1);
    }
    //check if file exists, if it doesn't exit program
    File file = new File(args[1]);
    if(!file.exists()) {
        System.out.println("The file " + args[1] + " does not exist");
        System.exit(2);
    }
    /*okay so, I need to remove all instances of the string from the file. 
     * replacing with "" would technically remove the string
     */
    try (//read in the file
            Scanner in = new Scanner(file);) {


        while(in.hasNext()) {
            String newLine = in.nextLine();
            newLine = newLine.replaceAll(args[0], "");
            }

    }

}

}

I don't quite know if I'm headed in the correct direction because I'm having some issue getting the command line to work with me. I only want to know if this is heading in the correct direction.

Is this actually changing the lines in the current file, or will I need different file to make alterations? Can I just wrap this in a PrintWriter to output?

Edit: Took out some unnecessary information to focus the question. Someone commented that the file wouldn't be getting edited. Does that mean I need to use PrintWriter. Can I just create a file to do so? Meaning I don't take a file from user?


Solution

  • Your code is only reading file and save lines into memory. You will need to store all modified contents and then re-write it back to the file.

    Also, if you need to keep newline character \n to maintain format when re-write back to the file, make sure to include it.

    There are many ways to solve this, and this is one of them. It's not perfect, but it works for your problem. You can get some ideas or directions out of it.

    List<String> lines = new ArrayList<>();
    try {
        Scanner in = new Scanner(file);
    
        while(in.hasNext()) {
            String newLine = in.nextLine();
            lines.add(newLine.replaceAll(args[0], "") + "\n"); // <-- save new-line character
        }
    
        in.close();
    
        // save all new lines to input file
        FileWriter fileWriter = new FileWriter(args[1]);
        PrintWriter printWriter = new PrintWriter(fileWriter);
        lines.forEach(printWriter::print);
        printWriter.close();
    
    } catch (IOException ioEx) {
        System.err.println("Error: " + ioEx.getMessage());
    }