the_no_1
the_no_1

Reputation: 25

How do I add / delete a line from a text file?

I am unsure on how to give the user an option to add / delete a name from the existing text file. The current code works fine and reads in names from the text file. Could someone give me a hand on this?

import java.io.File;
import java.util.Scanner;


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

  String[] names = new String[100];
  Scanner scan = new Scanner(new File("names.txt"));
  int index = 0;

  while (scan.hasNext()){
    names[index]=(scan.nextLine());
    index++;
  }

  for(int i = 0; i < index; i++){
    System.out.println(names[i]);
  }

    scan.close();
}


}

Upvotes: 0

Views: 1763

Answers (1)

Shadow
Shadow

Reputation: 4006

It is possible, almost everything is, but you'll find it very difficult to do using arrays.

I would instead use an ArrayList which is similar, but much, much better than just regular ol' arrays.

A String ArrayList is defined like so:

ArrayList<String> names = new ArrayList<String>();

You can add using the add function of the ArrayList:

while (scan.hasNext())
    names.add(scan.nextLine());

Then, to remove a name from the text file, just remove it from the names ArrayList using the remove function, and write the modified ArrayList to the file:

names.remove("Some Name Here");
PrintWriter writer = new PrintWriter("names.txt", "UTF-8");
for (int i = 0; i < names.size(); i++)
    writer.println(names.get(i));
writer.close();

Likewise, to add a new name to the file, just add the new name to the ArrayList before you write it to the file, using the add function

Upvotes: 1

Related Questions