-1

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?

user51
  • 8,843
  • 21
  • 79
  • 158
Alex
  • 31
  • 4
  • Possible duplicate of [Installing Java manually on Windows?](https://stackoverflow.com/questions/930265/installing-java-manually-on-windows) – Andronicus Mar 16 '19 at 05:07
  • I don't really understand how this applies to me? Care to explain? The issue there seems to be someone not wanting to install java with registry edits or how to install with a zip? – Alex Mar 16 '19 at 05:17
  • I wasn't sure which one to choose, but it clearly is the fault of not having java installed correctly – Andronicus Mar 16 '19 at 05:18
  • Your code is on the right track, but you're not writing anything to the file system so the file remains unchanged after your code runs. – D.B. Mar 16 '19 at 05:28
  • @D.B. Thanks, i'm assuming I'd need to use a PrintWriter then. My while loop isn't doing anything? – Alex Mar 16 '19 at 05:32
  • @Alex there are plenty of examples regarding how to do file I/O with Java including [tutorials on the oracle site](https://docs.oracle.com/javase/tutorial/essential/io/). Your while loop is creating a `String` in memory but never writes the string to a file. Take a look at tutorials and examples and I think you'll understand better. As an analogy it's like if you're reading a book and in your mind you remove "John" from each line of text while you're reading, but you never write down the resulting text so once it leaves your mind it's gone. – D.B. Mar 16 '19 at 05:38
  • @D.B Great analogy, thanks so much for that because I don't think I would've understood without it. I'll get to reading. – Alex Mar 16 '19 at 05:40

1 Answers1

0

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());
}
Pete Houston
  • 14,931
  • 6
  • 47
  • 60
  • Thanks for this. Quick question though, is this writing back to the same file? should the filewriter object be to args[0] instead of args[1]? I'm trying to understand everything, I'm on the api now, so I might just be confused. – Alex Mar 16 '19 at 06:03
  • Usage: `new FileWriter(String filename)` . So it will write into the `filename`, if it is the same name in argument then it re-writes to that existing file. – Pete Houston Mar 16 '19 at 06:05
  • Oh ok, that makes sense. I don't know what I was thinking. Thanks – Alex Mar 16 '19 at 06:06